[ Web Proxy ]
URL:
Viewing: https://javascript.info/task/let-scope [Back]  [Original]

Is variable visible?
EN

We want to make this open-source project available for people all around the world.

Help to translate the content of this tutorial to your language!

    Search on Javascript.info:
    Search in the tutorial:
    Light themeDark theme
    DanskEnglishEspaolFranaisIndonesiaItalianoTrkeOzbek
    back to the lesson

    Is variable visible?

    importance: 4

    What will be the result of this code?

    let x = 1;
    
    function func() {
      console.log(x); // ?
    
      let x = 2;
    }
    
    func();

    P.S. Theres a pitfall in this task. The solution is not obvious.

    solution

    The result is: error.

    Try running it:

    let x = 1;
    
    function func() {
      console.log(x); // ReferenceError: Cannot access 'x' before initialization
      let x = 2;
    }
    
    func();

    In this example we can observe the peculiar difference between a non-existing and uninitialized variable.

    As you may have read in the article Variable scope, closure, a variable starts in the uninitialized state from the moment when the execution enters a code block (or a function). And it stays uninitalized until the corresponding let statement.

    In other words, a variable technically exists, but cant be used before let.

    The code above demonstrates it.

    function func() {
      // the local variable x is known to the engine from the beginning of the function,
      // but "uninitialized" (unusable) until let ("dead zone")
      // hence the error
    
      console.log(x); // ReferenceError: Cannot access 'x' before initialization
    
      let x = 2;
    }

    This zone of temporary unusability of a variable (from the beginning of the code block till let) is sometimes called the dead zone.


    Web Proxy Viewer  |  New URL  |  Original Page