CRz
CRz

Reputation: 51

Block scoping with nested var shows different errors

I'm trying to understand block scoping on ES6 and found the following issue (maybe I'm just misunderstanding the concept):

In the first test I tried the following and got the commented error:

{
    const x = 2;
    console.log( x );   //2
    {
        let x = "b";
        console.log(x); //b
        {
            var x = true; //Identifier 'x' has already been declared
        }
    }

}
console.log(x)

But when I try to get the type of the "already declared" x I get :

{
    const x = 2;
    console.log( x );   //2
    {
        let x = "b";
        console.log(x);  //b
        {
            console.log(typeof x); //this throws Uncaught ReferenceError: x is not defined
        }
    }

}
console.log(x);

I'll keep trying to see what is going on, any ideas are accepted.

Upvotes: 0

Views: 34

Answers (2)

Moe kanan
Moe kanan

Reputation: 189

First of all, you need to know the difference between let and var

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope. An explanation of why the name "let" was chosen can be found here. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

Second, you got this error "Identifier 'x' has already been declared" because you already have "let x" so you can't use "var x". However, if you change the var to let, it will work.

Example to understand scoping:

function test() {     // first scope
   let x = 1;
   let y = 2;
   console.log(x, y); //1 2

   function test2() {  // second scope
     let x = 2;
     let z = 3;
     console.log(x,y,z); //2 2 3

   }
   test2();
   console.log(z); //z is not defined... notice z is defined in the second scope, not the first one
}
test();

Keep in mind, you can access variables from higher/global scopes in inner scopes, but you can't access variables from inner scopes in higher/global scopes.

Read this: What is the scope of variables in JavaScript?

EDIT:

If you do this, it should work fine

const x = 2;
console.log( x );   //2
{
    let x = "b";
    console.log(x); //b
    {
         x = true;
    }
}
console.log(x)

OR

const x = 2;
console.log( x );   //2
{
    let x = "b";
    console.log(x); //b
    {
        let x = true;
    }
}
console.log(x)

Upvotes: 0

SLaks
SLaks

Reputation: 887449

Actually, your error comes from the final console.log(x);. Removing that line makes your code work fine.

This error makes perfect sense. x is only defined in inner blocks; it doesn't exist in the outer scope.

Upvotes: 2

Related Questions