2
var a = 2;
var b = function(){
    console.log(a);
    var a = 1;
};
b();

When I call b, it prints undefined. What is the reason?

Anonymous
  • 11,748
  • 6
  • 35
  • 57
mahigupta
  • 89
  • 5

3 Answers3

2

Inside a function, var declares a function-scoped variable. That means it's visible to the function. The entire function. That means you are print out the variable before assigning a value to it.

var a = 123;
(function () {
    a = 456;         // Changes the function's "a"
    console.log(a);  // Outputs the function's "a": 456
    var a;           // At compile-time, declares a function variable named "a".
})();
console.log(a);      // Outputs the global "a": 123

Along the same line, repeating the declaration doesn't do anything. The following prints out 123.

(function () {
   var a = 123;
   var a;
   console.log(a);  // 123
})();
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • but in global scope its already declared..so why its not printing 2 ? – mahigupta May 28 '14 at 21:02
  • @mahigupta, Function-scoped variables have precedence. If it didn't, `var a = 123; (function () { var a = 456; alert(a); })();` would print `123`. – ikegami May 28 '14 at 21:04
  • @mahigupta, If you mean to ask *why aren't JS variables scoped from where they are declared to the end of the block or the next declaration of the same name?*, I have no idea. Worst JS "feature". – ikegami May 28 '14 at 21:08
1

The var a in your code is a variable declaration that declares a variable within the scope of its containing function. Due to variable hoisting, variable declarations (like var a) are hoisted to the top of their containing function. While any declaration is hoisted, assignments to that variable are not hoisted, Thus, your code is equivalent to:

var a = 2;
var b = function(){
    var a; // hoisted declaration; declares `a` within this function scope
    console.log(a);
    a = 1; // not-hoisted assignment
};
b();

Since a declared variable is undefined until it is given a value, this code logs undefined.

apsillers
  • 112,806
  • 17
  • 235
  • 239
0

You have this:

var a = 2;
var b = function(){
    console.log(a);
    var a = 1;
};

During the run time it becomes:

var a = 2, b;
b = function(){
    var a; // new variable declaration with no value assigned
    console.log(a); // You used it new "a" without assigning any value
    a = 1;
};

Inside the function the a is a new variable because of var keyword and JS is taking this new a in account which is undefined not the global a. Tow variables with same name, one is outside the function (in global scope) and another is inside the function. Since there is a new variable available inside the function so it's being used in console.log(a) but no value assigned.

You may read JavaScript Scoping and Hoisting and var on MDN.

The Alpha
  • 143,660
  • 29
  • 287
  • 307