javascript hoisting for global variable
Asked Answered
M

2

6

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??

Margoriemargot answered 5/11, 2014 at 9:6 Comment(3)
Basically: b=5; doesn't get hoisted. Only var statements do.Carri
So when I say b=5, it has a global scope, so why it's not take from global scope.Margoriemargot
thx alot, I learned a new thing about JavaScript :-) I also had a look at this: w3schools.com/js/js_hoisting.aspEffervescent
S
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).

Selfanalysis answered 5/11, 2014 at 9:8 Comment(2)
So when I say b=5, it has a global scope, so why it's not take from global scope.Margoriemargot
@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.Carri
A
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);
}
Amphi answered 23/3, 2022 at 22:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.