Home » Hoisting in JS

Hoisting in JS

Hoisting in JS

Introduction

Hoisting in JS, represents a key concept in JavaScript that can sometimes be confusing. It involves moving variable and function declarations to the top of their scope during the compilation phase. This feature enables the use of variables and functions before they are formally declared in the code. Understanding hoisting is beneficial in preventing unpredictable behaviors and facilitating the writing of more consistent JavaScript code.

How Hoisting Works?

In JavaScript, code execution occurs in two stages: compilation and execution. During the compilation phase, the engine locates all variable and function declarations, lifting them to the top of their scope—whether global or function scope. Consequently, variables and functions can be referenced prior to their actual declarations in the code.

However, while declarations are hoisted, initializations are not. For variables declared using var, the initialization defaults to undefined until they are explicitly assigned a value.

Variable Hoisting

Variables declared using var are subject to hoisting within their scope and are initialized with undefined. Consider the following to demonstrate this feature:

// Accessing variables before declaration
console.log(x); // Output: undefined
var x = 5;
console.log(x); // Output: 5
JavaScript

In the given example, the x variable declared with var is hoisted to the top of its scope. As a result, invoking console.log(x) before assigning a value of x will output undefine.

Function Hoisting

Function declarations also undergo hoisting to the top of their of scope, enabling them to be called prior to their actual declaration within the code. For example :

// Function declaration hoisting
getName();
//Output : 'Hello Hoister'
console.log(getName); 
// Output: function getName() {
// return 'Hello Hoister';
//}
function getName() {
  console.log('Hello Hoister');
}
JavaScript

In above code , getName function is hoisted , allowing it to be invoked before its declaration.

let and const Variables

Variables declared using let and const are hoisted like var but are not initialized with undefined. Instead, they enter a “temporal dead zone” from the beginning of the block until they are actually declared. Attempting to access them before their declaration will cause a ReferenceError.

let Example

console.log(name);
// Output : ReferenceError Cannot access 'name' before initialization
let name = 'JavaScript';
console.log(name);
//OutPut : 'JavaScript' as we can see we are calling this variable after initialization or declaration
JavaScript

const Example

console.log(subject);
// Output : ReferenceError Cannot access 'subject' before initialization
let subject= 'Mathematics';
console.log(subject);
//OutPut : 'Mathematics' as we can see we are calling this variable after initialization or declaration
JavaScript

Function expression and Arrow functions

in contrast to function declarations, function expressions and arrow functions do not exhibit hoisting in the same manner. They resemble var-declared variables where their initializations are not hoisted.

For Example :

console.log(greet);
//Ouput : ReferenceError: greet is not defined

const greet = function(name) {
  console.log('Yes it is working');
};
JavaScript

Arrow Function example :

console.log(greets); 
//Ouput : ReferenceError: greets is not defined

const greets = name => 'hello';

//But if we define greets with var it will give undefined due to hositing
console.log(greets);
//Ouput : undefined
var greets = name => 'hello';
JavaScript

Here’s what’s happening:

  • Variable Declaration and Initialization with var: The variable greets is also set, and its value is undefined because of hoisting. In other words, it means that there is memory space for greets, but it does not have any value for that memory space.
  • Accessing the Variable Before Initialization: You’re trying to console. log(greets) before the variable greets has been declared That means that log is called without an argument before any value has been assigned to the variable greets. At the time of writing the program, greets remains undeclared, which means it has not yet been assigned any value.
  • Arrow Function Assignment: After the console.log statement, greets is assigned an arrow function that returns the string ‘hello’.
  • Output: When you console.log(greets) before the assignment, it prints undefined because that’s the initial value assigned due to hoisting.

Conclusion

Hoisting is an important concept in JavaScript that shifts declarations to the beginning of their scope during the compilation phase. Familiarizing yourself with how hoisting functions with variable declarations, function declarations, function expressions, arrow functions, and variables declared using let and const can aid in producing JavaScript code that is more predictable and less prone to bugs. By becoming proficient in these concepts, you will be better equipped to manage JavaScript’s idiosyncrasies and subtleties effectively.

Frequently Asked Questions

1. What is hoisting in JavaScript?

Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase. This allows variables and functions to be used before they are actually declared in the code.

2.Which declarations are hoisted in JavaScript?

Variable declarations using var, let, and const, as well as function declarations, are hoisted in JavaScript.

3. What happens if I try to access a variable before it is declared in JavaScript?

If you try to access a variable before it is declared, it will result in a ReferenceError unless the variable is declared with var, in which case it will return undefined.