DEV Community

Sujit Singh
Sujit Singh

Posted on

Hoisting with var

I came across a lot of articles describing hoisting in Javascript.. where in a nutshell, most of them indicating it as a feature where variable declarations are moved to the top of their scope, and few of them even illustrating with appropriate examples with var, let and const.

With const and let having block level scope, it becomes easy to describe.. but I find var a bit tricky to crack hoisting with. Specially when I came across a problem faced by one of my colleague in one of the interviews.

So the problem is as follows whose output was asked to explain:

var num = 4;
function test() {
    var newNum = num;
    console.log('num outside loop:', num);
    for (var num = 0; num < newNum; num++) {
        console.log('num inside loop:', num);
    }
}
test();
Enter fullscreen mode Exit fullscreen mode

From first look, one can say it will be printing following:

num outside loop: 4
num inside loop: 0
num inside loop: 1
num inside loop: 2
num inside loop: 3
Enter fullscreen mode Exit fullscreen mode

But actually it prints:

num outside loop: undefined

Enter fullscreen mode Exit fullscreen mode

And thats it.. it doesn't even enters the loop.
Why so? Javascript hoisting kicks in and moves the num declaration at the top of the function test, so effectively it becomes:

var num; // hoisting
num = 4;
function test() {
    var num; // hoisting - redefines num as undefined
    var newNum;
    newNum = num; // undefined is assigned to newNum
    console.log('num outside loop:', num); // prints message followed by undefined
    for (num = 0; num < newNum; num++) { // var num declaration moved to top as a part of hoisting
        console.log('num inside loop:', num);
    }
}
test();
Enter fullscreen mode Exit fullscreen mode

It's clear that it will never execute the loop with new value of num i.e. 0 being compared to undefined value for newNum.

Thanks for reading through. Feel free to suggest corrections / additions if any.

Top comments (0)