Asad Iqbal Asad Iqbal - 1 month ago 5
Javascript Question

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

Ian Ian
Answer

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

Comments