350

I have been playing with ES6 for a while and I noticed that while variables declared with var are hoisted as expected...

console.log(typeof name); // undefined
var name = "John";

...variables declared with let or const seem to have some problems with hoisting:

console.log(typeof name); // ReferenceError
let name = "John";

and

console.log(typeof name); // ReferenceError
const name = "John";

Does this mean that variables declared with let or const are not hoisted? What is really going on here? Is there any difference between let and const in this matter?

Aditya Patnaik
  • 1,490
  • 17
  • 27
Luboš Turek
  • 6,273
  • 9
  • 40
  • 50

7 Answers7

451

@thefourtheye is correct in saying that these variables cannot be accessed before they are declared. However, it's a bit more complicated than that.

Are variables declared with let or const not hoisted? What is really going on here?

All declarations (var, let, const, function, function*, class) are "hoisted" in JavaScript. This means that if a name is declared in a scope, in that scope the identifier will always reference that particular variable:

x = "global";
// function scope:
(function() {
    x; // not "global"

    var/let/… x;
}());
// block scope (not for `var`s):
{
    x; // not "global"

    let/const/… x;
}

This is true both for function and block scopes1.

The difference between var/function/function* declarations and let/const/class declara­tions is the initialisation.
The former are initialised with undefined or the (generator) function right when the binding is created at the top of the scope. The lexically declared variables however stay uninitialised. This means that a ReferenceError exception is thrown when you try to access it. It will only get initialised when the let/const/class statement is evaluated, everything before (above) that is called the temporal dead zone.

x = y = "global";
(function() {
    x; // undefined
    y; // Reference error: y is not defined

    var x = "local";
    let y = "local";
}());

Notice that a let y; statement initialises the variable with undefined like let y = undefined; would have.

The temporal dead zone is not a syntactic location, but rather the time between the variable (scope) creation and the initialisation. It's not an error to reference the variable in code above the declaration as long as that code is not executed (e.g. a function body or simply dead code), and it will throw an exception if you access the variable before the initialisation even if the accessing code is below the declaration (e.g. in a hoisted function declaration that is called too early).

Is there any difference between let and const in this matter?

No, they work the same as far as hoisting is regarded. The only difference between them is that a constant must be and can only be assigned in the initialiser part of the declaration (const one = 1;, both const one; and later reassignments like one = 2 are invalid).

1: var declarations are still working only on the function level, of course

ruffin
  • 16,507
  • 9
  • 88
  • 138
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 1
    Ah, that was implied. Hoisting always happens inside a scope, and blocks are the scope for everything (except `var`). – Bergi Jan 09 '16 at 23:02
  • 33
    I find that something like `let foo = () => bar; let bar = 'bar'; foo();` illustrates *all declarations are hoisted* effect even better, because it is not obvious due to temporal dead zone. – Estus Flask Jul 19 '16 at 13:59
  • 2
    I was about to ask about referencing a let definition in a function declared before the let (ie a closure). I think this answers the question, it's legal but will be a ref error if the function is invoked before the let statement is executed, and will be fine if the function is invoked afterwards. perhaps this could be added to the answer if true? – Mike Lippert Oct 25 '16 at 18:07
  • 2
    @MikeLippert Yes, that is correct. You must not call the function that accesses the variable before it is initialised. This scenario occurs with every hoisted function declaration, for example. – Bergi Oct 25 '16 at 18:23
  • 1
    The decision to make `const` like `let` is a design flaw. Within a scope, `const` should have been made to be hoisted and just-in-time-initialized when it is accessed. Really, they should have a `const`, a `let`, and another keyword which creates a variable that works like a "readonly" `let`. – Pacerier Mar 22 '17 at 20:27
  • @Pacerier You seem to be asking for a `lazy const` keyword - which is a very good idea, but slightly esoteric and making evaluation order less obvious. Regardless, design discussions are off-topic here, you might want to head over to https://mail.mozilla.org/listinfo/es-discuss for that – Bergi Mar 22 '17 at 20:34
  • 1
    "*The former are initialised with undefined*…" might be ok for *var* declarations but does not seem appropriate for function declarations, which are assigned a value before execution begins. – RobG Mar 23 '17 at 06:12
  • @RobG It says "*`undefined` or the (generator) function*". Any idea how I can improve the wording? – Bergi Mar 23 '17 at 10:48
  • As noted in comments here https://stackoverflow.com/questions/46686413/var-and-let-redeclaration-in-javascript , hoisting is [not a precise term here](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting), because ES2015 defines it officially and it differs from its colloquial sense. – Estus Flask Oct 11 '17 at 13:49
  • @estus Yes, I don't like the term either (because, as MDN puts it, it implies that "*declarations are physically moved to the top of your coding, but this is not what happens at all*"). That's why I wrote immediately after it "*This means that…*". I'll edit to put the term in quotes, though. – Bergi Oct 11 '17 at 14:28
  • @EstusFlask Your example `let foo = () => bar; let bar = 'bar'; foo();` **doesn't** illustrate _all declarations are hoisted_. Consider `function foo() { const p = new Rectangle(); console.log(p); } class Rectangle {} foo();` This still works even that class declarations are not hoisted!! – user31782 Oct 13 '21 at 10:35
  • @user31782 It works precisely *because* `class` declarations are hoisted, as my answer explains. If it wasn't hoisted, you'd get a `ReferenceError`. – Bergi Oct 13 '21 at 10:37
  • @Bergi [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) says class declarations are not hoisted, see the _Hoisting_ section. – user31782 Oct 13 '21 at 10:39
  • @user31782 OK I'll fix MDN – Bergi Oct 13 '21 at 10:39
  • 1
    Farking hell mate, now I can't trust even MDN :-( – user31782 Oct 13 '21 at 10:40
  • @Bergi Did you manage to fix MDN? – user31782 Nov 02 '21 at 08:35
  • "The lexically declared variables however stay uninitialised." @Bergi, isn't var lexically scoped too? – isAif Jul 03 '22 at 05:38
  • @isAif Yes, JS fundamentally uses lexical scoping. However, `var` is scoped to the function in which it is declared in, not to the block, and the specification does not call it a *LexicalDeclaration*, which refers exclusively to `let` and `const`. – Bergi Jul 03 '22 at 09:02
  • > MDN now: This occurs because while the class is hoisted its values are not initialized. – Andres Zapata Jul 14 '22 at 21:40
115

Quoting ECMAScript 6 (ECMAScript 2015) specification's, let and const declarations section,

The variables are created when their containing Lexical Environment is instantiated but may not be accessed in any way until the variable’s LexicalBinding is evaluated.

So, to answer your question, yes, let and const hoist but you cannot access them before the actual declaration is evaluated at runtime.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • 6
    In other words, can we we say that: *only declarations are hoisted, not the initializations/assignments* – Zaheer Oct 05 '20 at 10:11
35

ES6 introduces Let variables which comes up with block level scoping. Until ES5 we did not have block level scoping, so the variables which are declared inside a block are always hoisted to function level scoping.

Basically Scope refers to where in your program your variables are visible, which determines where you are allowed to use variables you have declared. In ES5 we have global scope,function scope and try/catch scope, with ES6 we also get the block level scoping by using Let.

  • When you define a variable with var keyword, it's known the entire function from the moment it's defined.
  • When you define a variable with let statement it's only known in the block it's defined.

     function doSomething(arr){
         //i is known here but undefined
         //j is not known here
    
         console.log(i);
         console.log(j);
    
         for(var i=0; i<arr.length; i++){
             //i is known here
         }
    
         //i is known here
         //j is not known here
    
         console.log(i);
         console.log(j);
    
         for(let j=0; j<arr.length; j++){
             //j is known here
         }
    
         //i is known here
         //j is not known here
    
         console.log(i);
         console.log(j);
     }
    
     doSomething(["Thalaivar", "Vinoth", "Kabali", "Dinesh"]);
    

If you run the code, you could see the variable j is only known in the loop and not before and after. Yet, our variable i is known in the entire function from the moment it is defined onward.

There is another great advantage using let as it creates a new lexical environment and also binds fresh value rather than keeping an old reference.

for(var i=1; i<6; i++){
   setTimeout(function(){
      console.log(i);
   },1000)
}

for(let i=1; i<6; i++){
   setTimeout(function(){
      console.log(i);
   },1000)
}

The first for loop always print the last value, with let it creates a new scope and bind fresh values printing us 1, 2, 3, 4, 5.

Coming to constants, it work basically like let, the only difference is their value can't be changed. In constants mutation is allowed but reassignment is not allowed.

const foo = {};
foo.bar = 42;
console.log(foo.bar); //works

const name = []
name.push("Vinoth");
console.log(name); //works

const age = 100;
age = 20; //Throws Uncaught TypeError: Assignment to constant variable.

console.log(age);

If a constant refers to an object, it will always refer to the object but the object itself can be changed (if it is mutable). If you like to have an immutable object, you could use Object.freeze([])

Liren Yeo
  • 3,215
  • 2
  • 20
  • 41
Thalaivar
  • 23,282
  • 5
  • 60
  • 71
  • You don't answer the real question, if `let` variables are hoisted, why can't they be accessed? Or how do we prove that they are hoisted if theres no way to access them before they are declared. – user31782 Oct 12 '21 at 19:28
11

As per ECMAScript® 2021

Let and Const Declarations

  • let and const declarations define variables that are scoped to the running execution context's LexicalEnvironment.
  • The variables are created when their containing Environment Record is instantiated but may not be accessed in any way until the variable's LexicalBinding is evaluated.
  • A variable defined by a LexicalBinding with an Initializer is assigned the value of its Initializer's AssignmentExpression when the LexicalBinding is evaluated, not when the variable is created.
  • If a LexicalBinding in a let declaration does not have an Initializer the variable is assigned the value undefined when the LexicalBinding is evaluated.

Block Declaration Instantiation

  • When a Block or CaseBlock is evaluated a new declarative Environment Record is created and bindings for each block scoped variable, constant, function, or class declared in the block are instantiated in the Environment Record.
  • No matter how control leaves the Block the LexicalEnvironment is always restored to its former state.

Top Level Lexically Declared Names

At the top level of a function, or script, function declarations are treated like var declarations rather than like lexical declarations.

Conclusion

  • let and const are hoisted but not initialized.

    Referencing the variable in the block before the variable declaration results in a ReferenceError, because the variable is in a "temporal dead zone" from the start of the block until the declaration is processed.

Examples below make it clear as to how "let" variables behave in a lexical scope/nested-lexical scope.

Example 1

var a;
console.log(a); //undefined

console.log(b); //undefined
var b;


let x;
console.log(x); //undefined

console.log(y); // Uncaught ReferenceError: y is not defined
let y; 

The variable 'y' gives a referenceError, that doesn't mean it's not hoisted. The variable is created when the containing environment is instantiated. But it may not be accessed bcz of it being in an inaccessible "temporal dead zone".

Example 2

let mylet = 'my value';
 
(function() {
  //let mylet;
  console.log(mylet); // "my value"
  mylet = 'local value';
})();

Example 3

let mylet = 'my value';
 
(function() {
  let mylet;   
  console.log(mylet); // undefined
  mylet = 'local value';
})();

In Example 3, the freshly declared "mylet" variable inside the function does not have an Initializer before the log statement, hence the value "undefined".

Source

ECMA MDN

Aditya Patnaik
  • 1,490
  • 17
  • 27
7

From MDN web docs:

In ECMAScript 2015, let and const are hoisted but not initialized. Referencing the variable in the block before the variable declaration results in a ReferenceError because the variable is in a "temporal dead zone" from the start of the block until the declaration is processed.

console.log(x); // ReferenceError
let x = 3;
YourAboutMeIsBlank
  • 1,787
  • 3
  • 18
  • 27
  • 1
    It's `undefined` even in the case of `var`. Because, declarations are hoisted, not the initializations. If you first `initialize->access->declare`, in case of `var`, it will be hoisted, in case of `let` and `const`, it will have `ReferenceError` and will not be hoisted. – Zaheer Oct 05 '20 at 10:17
  • I think @Zaheer is right here; the language in your answer is muddy. You're referencing `x` before it's **initialized** but, because of hoisting, **not** before it's declared, so "_Referencing the variable in the block before the variable declaration_" is imprecise in this context if not inaccurate. Further, the "Temporal Dead Zone" is due to the variable not yet being _initialized_ -- "processed" seems too imprecise a term. – ruffin Dec 22 '22 at 21:24
4

in es6 when we use let or const we have to declare the variable before using them. eg. 1 -

// this will work
u = 10;
var u;

// this will give an error 
k = 10;
let k;  // ReferenceError: Cannot access 'k' before initialization.

eg. 2-

// this code works as variable j is declared before it is used.
function doSmth() {
j = 9;
}
let j;
doSmth();
console.log(j); // 9
user260778
  • 91
  • 1
  • 4
0

let and const are also hoisted. But an exception will be thrown if a variable declared with let or const is read before it is initialised due to below reasons.

  • Unlike var, they are not initialised with a default value while hoisting.
  • They cannot be read/written until they have been fully initialised.
Sai Kiran
  • 191
  • 1
  • 9