Skip to content
Advertisement

In the block scope even after initialisation with undefined var type of variable logs out unexpected value

function show() {
  var x = 10;
  if (true) {
    var x = 20;
  }
  console.log(x); // 20
}

show();

But when I not initialise the ‘x’ manually which is inside the ‘if-statement’, it initialise with undefined and hoisted to the top and should log the most recent value which is undefined , as 20 is logs out in the above example. But it logs out 10.Why?

function show() {
  var x = 10;
  if (true) {
    var x;
  }
  console.log(x); // 10
}

show();

Advertisement

Answer

From MDN - var:

Duplicate variable declarations using var will not trigger an error, even in strict mode, and the variable will not lose its value, unless another assignment is performed.

So, unless you re-assign any value to x, variable declared with var will keep its value.

Re-declaring x inside the if block does not create a new variable; x is created only once.

From the Ecmascript spec - 14.3.2 Variable Statement:

A var statement declares variables that are scoped to the running execution context’s VariableEnvironment. Var variables are created when their containing Environment Record is instantiated and are initialized to undefined when created. Within the scope of any VariableEnvironment a common BindingIdentifier may appear in more than one VariableDeclaration but those declarations collectively define only one variable.

That is why x in the following statement

var x;

doesn’t implicitly gets initialized with undefined; this re-declaration statement didn’t re-create the variable x.

function show() {
  var x = 10;
  if (true) {
    var x = undefined; // re-assigned
  }
  console.log(x);
}

show();

Note on hoisting: Unless you know this already, variables are NOT literally hoisted/moved to the top of the scope in which they are declared; variable declarations are processed before the code execution, this is why they appear to have moved to the top of the scope.

For more details, see: MDN - var hoisting

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement