JavaScript before executing your code reorders it according to some rules.

Functions in particular are moved at the top of their scope. This is why it’s legal to write

dosomething()
function dosomething() {
  console.log('did something')
}

Hoisting example

Internally, JavaScript moves the function before its call, along with all the other functions found in the same scope:

function dosomething() {
  console.log('did something')
}
dosomething()

Now, if you use named function expressions, since you’re using variables something different happens. The variable declaration is hoisted, but not the value, so not the function.

dosomething()
const dosomething = function dosomething() {
  console.log('did something')
}

This example is not going to work:

Hoisting named functions

This is because what happens internally is:

const dosomething
dosomething()
dosomething = function dosomething() {
  console.log('did something')
}

The same happens for let declarations. var declarations do not work either, but with a different error:

Hoisting var declarations

This is because var declarations are hoisted and initialized with undefined as a value, while const and let are hoisted but not initialized.


Go to the next lesson