5

I was wondering how javascript hoisting works for global variable.

Let's say I have following code snippet:

var a = 5;
function print(){
    console.warn("a",a,b);
    var a = 10;
    b=5;
    console.warn("a",a);
}
print();

In this case I am getting error "b is not defined". I wonder why Javascript hoisting is not working for global variable. I tried to look for this but getting results only for variable hoisting. Any thoughts??

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Mayank
  • 112
  • 8

2 Answers2

4

var statements are hoisted. function declarations are hoisted. Assignments are not hoisted (to the extent that if you combine a var statement with an assignment (var foo = 1) then the declaration part is hoisted but the assignment is not).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 1
    So when I say b=5, it has a global scope, so why it's not take from global scope. – Mayank Nov 05 '14 at 09:32
  • 1
    @Mayank: The whole `b` variable _does not get hoisted_. This means, at the time of `console.warn("a",a,b);`, `b` does not exist yet. – Cerbrus Nov 05 '14 at 09:32
0

Your code is reinterpreted as:

function print(){
    var b
    console.warn("a",a,b); // b is not assigned yet so it's undefined.
    var a = 10;
    b=5;
    console.warn("a",a);
}