0
 var x = 5;

 function a() {

     function b() {
         console.log(x);
     }

     b();
     var x = 6;
 }

 a();

In console.log(x), output is undefined. But if I change to,

 var x = 5;

 function a() {

     function b() {
         console.log(x);
     }
     b();
     x = 6; // remove `var`
 }

 a(); 

then output is 5.

Why this behaviour? Please explain me.

0

1 Answer 1

2

In the first example the local variable x is hoisted to the top of the scope, i.e. the function where it is declared. It works the same as if it was declared at the top:

var x = 5;

 function a() {
     var x;

     function b() {
         console.log(x);
     }

     b();
     x = 6;
 }

 a();

As the local variable isn't assigned a value before the function b is called, it's contains undefined.

Sign up to request clarification or add additional context in comments.

1 Comment

Per ECMA-262 at step 8 c ii, variables created through a variable declaration are initially assigned a value of undefined, so return undefined until assigned some other value.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.