0

why does the following code segment generate the following output?

code segment:

var a = 10;
function(){
    console.log(a);
    var a = 5;
}

output:

undefined
Rajesh Paul
  • 6,793
  • 6
  • 40
  • 57
  • 1
    [Javascript Scope And Hoisting](http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html#declarations_names_and_hoisting) – Patrick Evans Nov 29 '14 at 06:03

1 Answers1

3

Because variable is hoisted at top and in your function you have declared the variable var a = 5 which is same as following:

var a = 10;
function(){
    var a; // a = undefined
    console.log(a);//a is not defined so outputs undefined
    a = 5;
    console.log(a);//a is now 5 so outputs 5
}

And in your function scope var is being declared it doesn't see global variable but local variable i.e. var a and which is undefined.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231