Hoisting in JavaScript

Hoisting in JavaScript

One of the interesting aspects of JavaScript for new JavaScript developers is the fact that we can make things available before declaring them. It may sound weird. Let us understand the concept of hoisting in JavaScript in detail with this blog. 

What is hoisting in JavaScript?

The process of shifting the declaration of variables, functions, and classes to the top of their scope before the execution of code is called hoisting in JavaScript. It allows us to call the functions before including them in the code. Let’s look at some code examples.

Let us take some of the cases and see their output.

Case 1

console.log(helloWorld)

You will get the output as shown below

Uncaught ReferenceError: helloWorld is not defined

Case 2

console.log(greeting)

var greeting = “Hello World”

You will get the output as shown below

Undefined

Case 3

var greeting

console.log(greeting)

You will get the output as shown below

Undefined

The outputs may surprise you. Let us understand the reason behind the following outputs.

In case 1 the output is Uncaught TypeError: hello world is not defined but in case 2 and case 3 the output is undefined instead of throwing an error. The interpreter separates the assignment and declaration of variables and functions. And the declaration part is hoisted to the top of the respective scope of the variable or function. Note that hoisting occurs before the code execution. 

Variable Hoisting in JavaScript

We can use the variables in JavaScript in code before declaration by hoisting them. JavaScript doesn’t hoist initializations. In JavaScript, we declare the variables using the statements let, const, and var. We can also declare and assign in the same step. The variable hoisting depends on the keyword with which we hoist them. Let us discuss some of them.

1) var hoisting

The var keyword is used to declare a variable. When we hoist a variable declared with var, we initialize the value of the variable to undefined as seen in cases 2 and 3. The declarations made by var are processed before the execution of code and this is known as hoisting. The duplicate declarations made with var do not throw any error and the value of the variable is not lost until and unless another assignment is executed. The hoisting will affect the declaration of the variable but will not affect the initialization. Let us dive into code for better understanding.

Example 01

var greeting

greeting = “Hello World”

// is same as 

greeting = “Hello World”

var greeting

Example 02

console.log(greeting);    // returns output as undefined

var greeting = “ Hello World “;

console.log(greeting);    // returns output as Hello World

// is same as

var greeting

console.log(greeting)    // returns output as undefined

greeting = “ Hello World “

console.log(greeting)    // returns output as Hello World

2) let hoisting

The variables declared by using the let keyword are not function scoped but are block-scoped. These are hoisted but not initialized to a default value like that of the var statement. So it returns ReferenceError instead of undefined

Let us see an example

console.log(greeting)
let greeting;

You will get the output as shown below

Uncaught ReferenceError: Cannot access ‘greeting’ before initialization

We get the output as shown above when accessing a let variable before declaring it. However, when using the var statement we get the output as undefined instead of it throwing an error.

Let us see another example

let greeting = 'HelloWorld'

console.log(greeting)

console.log(YourName)

let YourName = ‘Kevin‘

You will get the output as shown below

HelloWorld

ReferenceError

In the first part, we got the desired output but in the latter, we got an error. This is because of the temporal dead zone. This zone starts at the beginning of the enclosing scope of variable and ends after it gets declared. Any attempt of accessing the variable in the temporal dead zone throws an error.

3) const hoisting

The variables declared using the const keyword act similar to the variables declared using the let keyword. The variables declared using the const keyword are block-scoped and immutable too. It means that once a value is assigned to a variable using the const keyword, this variable can’t change its value under any circumstance. You must specify the value of the variable declared by const keyword at the time of its declaration i.e. the declaration and the initialisation are done in the same statement strictly. The variables declared using the const keyword are uninitialized at starting of the code execution like in the case of the let keyword and unlike in the case of the var keyword. Let us see some more examples

Example 01

const greeting

You will get the output as shown below

// Uncaught SyntaxError: Missing initialiser in the const declaration

Example 02

console.log(yourName)    // This throws a reference error
const yourName = ‘CODEDAMN‘    
yourName = ‘codedamn‘    // This throws error as the variable is immutable

Function hoisting in JavaScript

Function declarations can also get hoisted. And they are hoisted to the top of their scope. A function can be called even before it is defined. But note that in the case of function expressions, the variables they are assigned to get hoisted instead.

Let us check these two code snippets. In the first code, we call the function before it is declared and in the second code, we call the function after it is declared.

Method 1

myName("Rahul");

let myName = (name) => {
  console.log("My name is " + name);
}

Method 2

let myName = (name) => {
  console.log("My name is " + name);
}

myName("Rahul");

In the first snippet, we get a not defined error. And the second snippet logs the desired statement in the console.

Conclusion

A proper understanding of this concept will be highly helpful for your code development. This was all about Hoisting in JavaSript. If you are interested in learning JavaScript, do check out the Javascript courses and articles on Codedamn. It offers a browser built-in playground to learn and practice code. Join the discord community of codedamn and never miss out on any new programs and updates.

Sharing is caring

Did you like what Agam singh, Aman Ahmed Siddiqui, Aman Chopra, Aman, Amol Shelke, Anas Khan, Anirudh Panda, Ankur Balwada, Anshul Soni, Arif Shaikh, wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far

Curious about this topic? Continue your journey with these coding courses: