DEV Community

Lucas Paganini
Lucas Paganini

Posted on • Originally published at lucaspaganini.com

JavaScript Hoisting and Function Types

Declarations, Expressions and Statements


See this and many other articles at lucaspaganini.com

We have two ways of defining functions in JavaScript:

  1. Functions declarations (AKA functions statements)
function add(a, b) {
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode
  1. Function expressions
const add = function (a, b) {
  return a + b;
};
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
Hoisting

1 - Function declarations
2 - Code execution
2.1 - Function expressions
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

References

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

Top comments (0)