SiteMap  | About    

What is function hoisting?

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. Basically, the JavaScript interpreter "looks ahead" to find all the variable declarations and "hoists" them to the top of the function. It is very important to note that initializations and assignments are not hoisted in JavaScript, only declarations are. While this does provide a basic understanding of how JavaScript scoping works, a deeper dive helps to build a stronger foundation.

There are 2 ways of creating functions in JavaScript , through Function Declaration and through Function Expression. Let’s see what these are and how hoisting affects them.

Consider the following example:

You will get the outpu "Call me...".

Here you can see the function callEralier() calling before declaring it. That means JavaScript hoisting the function here.

But, only declarations are hoisted

Consider the following example:

As we can see above, the variable declaration var tempCall is hoisted but it's assignment to a function is not. Therefore, the interpreter throws a TypeError since it sees expression as a variable and not a function. And that is how variable and function hoisting works in JavaScript. (C) 2018    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.