JavaScript Hoisting Explained

Did you ever wondered why you were able to invoke functions before the declaration of the function in your code? That’s the magic of JavaScript Hoisting.

We know that JavaScript is a interpreted language and the codes get executed from top to bottom, line-by-line in order. Well, that’s true for most cases except variables and function declarations statements.

JavaScript interpreter pre-processes all variables and function declarations statements and hoist (move up) them to top their respective scope and then the code execution is started.

Don’t worry if this sounds confusing to you a will go through details with examples to make it easier for you to understand.

Types of Hoisting

  • Variable Hoisting
  • Function Hoisting

Variable Hoisting

Consider the following statement, here we are trying to access an undeclared variable and we know it will throw a ReferenceError.

console.log(foo) // ReferenceError: foo is not defined

Now let’s try the following, this won’t throw any error. Because the variable declaration will get hoisted by JavaScript interpreter.

console.log(foo); // undefined
var foo;

Hoisting only moves the declaration, assignments are left in place. You can examine it by the following snippet. Even there is a value assigned, it will still output undefined.

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

This is how the interpreter runs the code after hoisting. It moves the declaration to the top, assignment and others are left in place.

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

Function Hoisting

Function hoisting is bit more interesting than variable hoisting. Let’s have a look at the following code snippet.

foo() // This function is going to be hoisted!

function foo(){
console.log('This function is going to be hoisted!')

As you can see, the foo() function has been invoked before it’s declared. But it will work fine because of hoisting.

Be careful about function expression though. Likewise variable assignments, function expressions isn’t hoisted. So the following code will through an error.

foo() // TypeError: foo is not a function

var foo = function(){
console.log('This function is going to be hoisted!')


Hoisting is a JavaScript mechanism where variables and function declarations are hoisted (moved up) to the top of their respective scope before the code gets executed.

So far we’ve discussed JavaScript Hoisting in the context of global scope. For local scope, the declarations of variables and functions are hoisted to their respective local scope, not at the global scope.

If you stuck with hoisting try to play around with it. It’s always best practice to avoid using functions and variables before declaring. Declaring first will reduce the chance of unnecessary bugs by hoisting.

Feel free leave your comment below for any further query.

Happy Coding 🙂

This Post Has 4 Comments

    1. Glad you liked it. 🙂

    1. Thanks Bablofil

Leave a Reply

Close Menu