Hoisting in JS in one minute

Check out the following code snippet:

foo = 'foo';
console.log(foo); //foo
var foo;
console.log(bar); //undefined
var bar = 42;

The difference between these two examples are the place where the variable declaration happens.

The magic is that during compile time, all declarations “moves” to the top of the scope in which it is defined. So after compilation the structure of the previous examples will be something like this:

var foo;
foo = 'foo';
console.log(foo); //foo
var bar;
console.log(bar); //undefined
answer = bar;

This phenomenon is why it doesn’t matter in which order you declare your functions in the code.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.