DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,274 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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)

This post blew up on DEV in 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!