Are let and const Hoisted in JavaScript?

When you declare a variable using let or const, it is actually hoisted, but its assignment is not. This means that:

  • The variable gets created when its containing block-scope is initialized;
  • The variable is not initialized to any value at the time of its creation;
  • The value you assign to the variable is not accessible till the actual let or const statement is evaluated;
  • Accessing the variable before the declaration results in a ReferenceError.

For example, a ReferenceError is thrown if a variable declared with let or const is read before it is initialized:

{
    // ReferenceError: x is not defined
    console.log(x);

    const x = 'foo';
}

This happens because the variable is in a "temporal dead zone" from the start of the block (i.e. time when the variable is created) until the declaration is processed (i.e. time when the variable is evaluated). The variable is only accessible and initialized once the let or const statement is evaluated:

{
    const x = 'foo';
    console.log(x); // 'foo'
}

Compare this to the following, where a function is able to access a let variable before the position at which it is declared (without raising any error):

{
    const func = () => console.log(x);

    const x = 'foo';

    func(); // 'foo'
}

This works without throwing any errors because the call to the function is made outside the "temporal dead zone" for the variable "x", at which point the variable declaration has already been processed.

As a rule of thumb, you should declare your variables before you use them to avoid confusion and to promote readability of your code.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.