JavaScript Hoisting and Function Types

JavaScript Hoisting and Function Types

We have two ways of defining functions in JavaScript:

  1. Functions declarations (AKA functions statements)
TypeScript
function add(a, b) {
  return a + b;
}
  1. Function expressions
TypeScript
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.

markdown
1 - Code execution
1.1 - Function declarations
1.2 - Function expressions
markdown
Hoisting

1 - Function declarations
2 - Code execution
2.1 - Function expressions

That's why we can use them before their declarations.

TypeScript
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.

TypeScript
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.

TypeScript
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 I’ll see you soon.

References

  1. Function expressions on MDN
  2. Function declarations on MDN
  3. Arrow function expressions on MDN

Join the newsletter and be the first to know when I launch a course, post a video or write an article.

I don't SPAM, one email per week tops.