JavaScript Hoisting

One of the interesting and core concept of JavaScript is Hoisting. In this post we will understand it with some example.

When we make a variable using var, the js interpreter hoists that variable to the top(inside of its lexical scope). Look at this code,

console.log(a)
var a = 10

Run the program you can see the output is undefined. Why? Isn’t the output a is not defined? as a is not declared before the console statement. This is happening actually,

// after hoisting
var a
console.log(a)
a = 10

You can see the var a is moved to the top so when we console the variable it shows undefined. This is called hoisting or variable hoisting, whenever we declare a variable with var the JS interpreter hoists that variable to the top.

Like variable, function can also be hoisted.

// step 1 - before hoisting
console.log(foo());
function foo() {
    var text = "I love JS";
    return text;
}

// step 2 - after hoisting
function foo() {
    var text = "I love JS";
    return text;
}
console.log(foo());

As you can see in step 1 the foo() function is called in the console statement before it’s declaration. But in step 2 or after hoisting the foo() function is moved to the top so we can run the program.

Another example that most of the interviewer loved to ask.

var name = "John"

function foo() {
    console.log(name)
    var name = "Mark"
}

console.log(name)
foo()

What is the output for the following example?

Output is John and undefined.

When we call the foo() function, the JavaScript interpreter goes to the function foo() and see we are declaring name again with var. So by the declaration of name in the foo() , the name variable will create a local scope. As a result that of that scope the name variable inside foo() can’t change the global variable name. So the global variable name stays the same and name variable inside the foo() hoist itself within its local scope.

This is what actually happening,

Remember always declare variable in the top.

2 thoughts on “JavaScript Hoisting

Leave a Reply

Your email address will not be published. Required fields are marked *