Declarations vs Expressions in ES6

There are some subtle differences between declarations and expressions. Here we take a look at the differences such as syntax, readability, debugging and more.

Syntax:

function myDeclarationFunction() {
}

Expressions have two types
1) anonymous:

const myAnonymousExpressionFunction = function() {
}

2) named:

const myNamedExpressionFunction = function named() {
}

Readability:

As Declarations start with the word function, they are often easier to recognise as functions earlier when you scan the code. Expressions also require more characters to write so take longer to read.

Debugging:

Declaration names always appear in the error stack so its easy to see where an error comes from. However with expressions it is easy to add them as anonymous by accident (as opposed to named) and not notice until you receive ‘anonymous’ inside the error stack. At which point you might waste several hours trying to find the source.

Hoisting:

This is somewhat contentious. Declarations hoist whereas Expressions don’t. This means declarations can be defined after they are called and the program wont error, due to being loaded before the code is executed. So you don’t need to worry about where they are declared. Expressions will error if they are not defined before they are used.
Some people prefer to have hoisting available whereas others like to rely on being explicit and treat the feature as magic. I think this one depends on personal preference.

Arrow Functions:

This a feature not available to declarations, whereas an expression can do something like the below:

const myNamedExpressionFunction = () => { 
}

Compiles to:

var myNamedExpressionFunction = function myNamedExpressionFunction() {
}

Functional Programming:

In javascript functions are first-class citizens. While both declarations and expressions can be used in a functional manner (for example callbacks) expressions are much easier to work with and are the preferred way to move functions around.

Conclusion

While they both have pro’s and con’s, I prefer to use declarations for functions which are always run, and expressions for dynamic purposes (callbacks, run conditionally).

If you see anything that you dont think is correct please comment/message me. Thanks

Leave a Reply