-4
 a = 10;

function abc() {
 console.log(" a is " + a);
var  a =5;
console.log("after a is " + a);
}

abc();

In this code above , my first console.log is showing a as undefined whereas the second console.log is showing the result of a as 5.

I am still trying to understand why my first console is showing a as undefined. I already defined variable a as a global variable.

zer00ne
  • 41,936
  • 6
  • 41
  • 68
dip
  • 1,241
  • 2
  • 18
  • 32

2 Answers2

5
function abc() {
 console.log(" a is " + a);
var  a =5;
console.log("after a is " + a);
}

this is turned into because of hoisting

function abc() {
 var a;
 console.log(" a is " + a); // undefined
a =5;
console.log("after a is " + a); // 5
}

javascript has lexical scope so the function will look for a in itself before looking outside and since it finds a = 5 ,it will hoist it's declaration.

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
1

This because the variable a has been declared again. No matter at which line you declare, the variable a has block-level-scope .

The case is undefined because, var a at that time is declared but is not supplied with any value.

This is what we call as "Hoisiting" i.e.

Function declarations and variable declarations are always moved (“hoisted”) invisibly to the top of their containing scope by the JavaScript interpreter

Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47
  • `the variable a has block-level-scope` are you sure? javascript variables don't have block scope, they are function scoped. – gurvinder372 Jan 04 '16 at 06:37