Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does JavaScript hoist variables?

I know that JavaScript moves all variable declarations to the top of the function. However, I was expecting same result in both console.log() below. However, I get NaN in first case and 4 in second.

Can someone explain this? I know there are similar questions already asked and answered on StackOverflow, but this question has something to do with the function definition. e.g., Does JavaScript move function variables to the end of variable declarations?

var doB = function() { return a+1};
var b = a+1;
var a = 3;
console.log(b); // NaN
console.log(doB()); // 4
like image 456
Asad Iqbal Avatar asked Jan 13 '23 11:01

Asad Iqbal


1 Answers

Because of hoisting, this is what your code technically looks like:

var doB, b, a;
doB = function() {
    return a+1;
};
b = a + 1;
a = 3;
console.log(b); // NaN
console.log(doB()); // 4

Because the code is executed from top to bottom, when b is initialized to a + 1, a hasn't been initialized to anything yet (it's undefined). So really, b tries to be set as undefined + 1, which is NaN

like image 90
Ian Avatar answered Jan 18 '23 07:01

Ian