Declarations, Expressions and Statements
See this and many other articles at lucaspaganini.com
We have two ways of defining functions in JavaScript:
- Functions declarations (AKA functions statements)
function add(a, b) {
return a + b;
}
- Function expressions
const add = function (a, b) {
return a + b;
};
Their differences lie not only in the syntax but also in the order that they're loaded.
Hoisting
Function declarations are loaded before the code execution, that process is called hoisting.
1 - Code execution
1.1 - Function declarations
1.2 - Function expressions
Hoisting
1 - Function declarations
2 - Code execution
2.1 - Function expressions
That's why we can use them before their declarations.
add(1, 2);
//=> 3
function add(a, b) {
return a + b;
}
add(1, 2);
//=> 3
Functions expressions, on the other hand, are treated as regular JavaScript values, just like a number
, string
or boolean
. You can assign them to a variable, but they're not hoisted, you need to declare them before usage.
add(1, 2);
//=> TypeError: add is not a function
const add = function (a, b) {
return a + b;
};
add(1, 2);
//=> 3
Arrow Functions
Another difference is that you can't have arrow function declarations. All arrow functions are expressions.
add(1, 2);
//=> TypeError: add is not a function
const add = (a, b) => a + b;
add(1, 2);
//=> 3
Conclusion
References are below.
If you enjoyed the content, you know what to do. Subscribe if you want to know more about JavaScript and web development in general.
Have a great day and see you soon.
Top comments (0)