Skip to content

Hoisting

SimonPlanje edited this page Jun 21, 2020 · 2 revisions

Hoisting

In the following example JavaScript does know there is a var d being declared, this declaration gets hoisted to the top but the assigning of the value to the variable comes later and does not get hoisted. So the following code will give back an value of undefined, because the declaration goes to the top and the assignment stays at the bottom.

console.log(d); // undefined
var d = 3;

You could do it like this for example:

d = 3;

console.log(d); //3

var d;

But how does this work with functions?

Named functions always get hoisted to the browser:

console.log(hoistMe);// 10

function hoistMe() {
var a = 10;
return a;
}

Like the example above the full function gets hoisted to the top because it is as well the declaration as the assigning.

When you link an unnamed function to a variable the function does not get hoisted to the top, only the deceleration of the var gets hoisted. In most situations you would use the following example because the function does not get hoisted and by that takes up less space.

**So this will work 👍 **

var a = function() {
var a = 20;
return a;
}
console.log(a());

**And this will not work 👎 **

console.log(a());

var a = function() {
var a = 20;
return a;
}

Sources

Clone this wiki locally