Olivier Pons
Olivier Pons

Reputation: 15788

Why do I have "i is not defined" instead of 'i' has already been declared

Why, with this code, the first console.log() generates an error (surprise, because I thought this behavior was only with var, not let):

(function() {
    "use strict";
    let i=12;
    function test() {  
        console.log(i);   
        let i=4544444;     
        console.log(i);     
    };
    test();
})();

do I get:

Uncaught ReferenceError: i is not defined

? Moreover, if I comment those lines:

(function() {
    "use strict";
    let i=12;
    function test() {  
        console.log(i);   
        //let i=4544444;     
        //console.log(i);     
    };
    test();
})();

Then it works (I thought with "use strict" you cant have variables with the same name at the same time)

Upvotes: 0

Views: 552

Answers (2)

Arvind Pal
Arvind Pal

Reputation: 521

let keyword has limited scope to the block, statement, or expression on which it is used. As in your case First let i = 12 has scope of entire block but second let i = 4544444 has scope of test function block so in this block before declare i, you are using i in console.log, so this generating Uncaught ReferenceError: i is not defined and when you comment the let i = 4544444 then i of value 12 is used

reference to let keyword scope

Upvotes: 0

zelda11
zelda11

Reputation: 433

let variables are registered at the top of the block. But when the variable is accessed before declaration, JavaScript throws an error: ReferenceError: is not defined. From the declaration statement up to the beginning of the block the variable is in a temporal dead zone and cannot be accessed.

function isTruthy(value) {  
  var myVariable = 'Value 1';
  if (value) {
    /**
     * temporal dead zone for myVariable
     */
    // Throws ReferenceError: myVariable is not defined
    console.log(myVariable);
    let myVariable = 'Value 2';
    // end of temporary dead zone for myVariable
    console.log(myVariable); // => 'Value 2'
    return true;
  }
  return false;
}
isTruthy(1); // => true 

Source: https://dmitripavlutin.com/javascript-hoisting-in-details/

Upvotes: 1

Related Questions