JavaScript Hoisting and Function Types
JavaScript Hoisting and Function Types
We have two ways of defining functions in JavaScript:
- Functions declarations (AKA functions statements)
function add(a, b) {
return a + b;
}TypeScriptfunction add(a, b) {
return a + b;
}- Function expressions
const add = function (a, b) {
return a + b;
};TypeScriptconst 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 expressionsmarkdown1 - Code execution
1.1 - Function declarations
1.2 - Function expressionsHoisting
1 - Function declarations
2 - Code execution
2.1 - Function expressionsmarkdownHoisting
1 - Function declarations
2 - Code execution
2.1 - Function expressionsThat's why we can use them before their declarations.
add(1, 2);
//=> 3
function add(a, b) {
return a + b;
}
add(1, 2);
//=> 3TypeScriptadd(1, 2);
//=> 3
function add(a, b) {
return a + b;
}
add(1, 2);
//=> 3Functions 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);
//=> 3TypeScriptadd(1, 2);
//=> TypeError: add is not a function
const add = function (a, b) {
return a + b;
};
add(1, 2);
//=> 3Arrow 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);
//=> 3TypeScriptadd(1, 2);
//=> TypeError: add is not a function
const add = (a, b) => a + b;
add(1, 2);
//=> 3Conclusion
References are below.
If you enjoyed the content, you know what to do.
Have a great day and see you soon.