javascriptjavascript-scope

JavaScript: understanding scope chain


What is the scope chain in following code snippet -

var name = 'John';

function foo() {
  if (false) {
    var name = 'James';
  }
  console.log(name);
}

foo();

I got couple of queries regarding this -


Solution

  • Yes this is because the variables declared with var have function scope and they are hoisted to the top of the function. It logs undefined due to hoisting.

    Variables declared with let have block scope so until the if block is not executed the variable name is not declared.

    Even if you change it with if(true) it will not work because the variable will only be available inside the block. {} not outside.

    Here is the example how let works.

    if(true){
      let x = 3
    }
    console.log(x);