<img alt="" src="https://secure.leadforensics.com/150446.png " style="display:none;">
Go to top icon

Hoisting in JavaScript

Ajit Sakhare Feb 26, 2019

Java Development JavaScript Application Development Hoisting

Generally, we all have heard of the term ‘hoisting’ with reference to flag hoisting.

Well even in JavaScript, it is used in a similar context. Instead of a flag, we are hoisting the functions and variable declarations here.
Functions and variable declarations are taken to the top of the functions they are executing in. If there is no parent function present, then they are hoisted to the top of the global scope.
Still, there are differences in what should be hoisted and how much to be hoisted.

Below are the different use cases, language behavior and their explanations. Hope it will help you in understanding hoisting better.

1. Variables

Only declarations are hoisted, a memory placeholder is granted which points to undefined as of now. Definitions still execute at the same place where the code is written.

console1

2. Functions

In the case of functions, the behavior becomes a little tricky. Functions are hoisted along with their body. This is the reason why we can call a function even before it’s declaration. Still they work just fine.

console 2

3. Statements and definitions

Statements and definitions stay in the same place where they are written and are not hoisted anywhere. Printing a value before it’s definition will still give us expected results which can be an ‘undefined’ or previously provided value depending upon our code.

console 3

4. Named function expression

Named function expression are executed in the same way as variables i.e. they will also return ‘undefined’ if called before it’s definition. This is because we are only assigning an anonymous function to a variable. Since the variable definition is not executed during hoisting, it will not know anything about the assigned anonymous function until the definition is executed.

console 4

It is important to understand this behavior as it could affect our code outputs and the way our code is parsed and executed.

I hope this blog was helpful in making you understand the hoisting in JavaScript.

e-Zest is a leading digital innovation partner for enterprises and technology companies that utilizes emerging technologies for creating engaging customers experiences. Being a customer-focused and technology-driven company, it always helps clients in crafting holistic business value for their software development efforts. It offers software development and consulting services for cloud computing, enterprise mobility, big data and analytics, user experience and digital commerce.