DEV Community

Abhay Yt
Abhay Yt

Posted on

Understanding Hoisting in JavaScript

Hoisting in JavaScript

Hoisting is a JavaScript mechanism where variables, functions, and classes are moved to the top of their scope during the compilation phase, before code execution. This allows you to use variables and functions before they are declared in the code.


1. How Hoisting Works

In JavaScript, declarations are hoisted to the top of their scope:

  • Variable declarations (with var, let, const)
  • Function declarations
  • Class declarations

However, only the declarations are hoisted, not the initializations or assignments.


2. Hoisting with Variables

A. var Keyword

Variables declared with var are hoisted and initialized to undefined. This means you can use them before their declaration, but their value will be undefined until assigned.

Example:

console.log(a); // Output: undefined
var a = 10;
console.log(a); // Output: 10
Enter fullscreen mode Exit fullscreen mode

B. let and const Keywords

Variables declared with let and const are hoisted but not initialized. Accessing them before their declaration will result in a ReferenceError. This is due to the temporal dead zone (TDZ).

Example:

console.log(b); // ReferenceError: Cannot access 'b' before initialization
let b = 20;

const c = 30;
console.log(c); // Output: 30
Enter fullscreen mode Exit fullscreen mode

3. Hoisting with Functions

A. Function Declarations

Function declarations are hoisted along with their definitions. You can call a function before it is defined in the code.

Example:

sayHello(); // Output: Hello!

function sayHello() {
  console.log("Hello!");
}
Enter fullscreen mode Exit fullscreen mode

B. Function Expressions

Function expressions are hoisted only as variables. Their actual function definitions are not hoisted, so calling them before their declaration will result in an error.

Example:

sayHello(); // TypeError: sayHello is not a function

var sayHello = function () {
  console.log("Hello!");
};
Enter fullscreen mode Exit fullscreen mode

C. Arrow Functions

Arrow functions behave like function expressions and are not hoisted with their definitions.

Example:

sayHello(); // ReferenceError: Cannot access 'sayHello' before initialization

let sayHello = () => {
  console.log("Hello!");
};
Enter fullscreen mode Exit fullscreen mode

4. Hoisting with Classes

Class declarations are hoisted, but their definitions are not initialized. Accessing a class before it is declared will result in a ReferenceError.

Example:

const person = new Person(); // ReferenceError: Cannot access 'Person' before initialization

class Person {
  constructor(name) {
    this.name = name;
  }
}
Enter fullscreen mode Exit fullscreen mode

5. Hoisting in the Global and Function Scope

  • Global Scope: Declarations are hoisted to the top of the global execution context.
  • Function Scope: Inside functions, declarations are hoisted to the top of the function's execution context.

Example:

function testHoisting() {
  console.log(x); // Output: undefined
  var x = 5;
  console.log(x); // Output: 5
}

testHoisting();
Enter fullscreen mode Exit fullscreen mode

6. Common Pitfalls of Hoisting

A. Undefined Values with var

console.log(name); // Output: undefined
var name = "John";
Enter fullscreen mode Exit fullscreen mode

B. Temporal Dead Zone with let and const

console.log(age); // ReferenceError
let age = 30;
Enter fullscreen mode Exit fullscreen mode

C. Confusion Between Declarations and Initializations

greet(); // Output: Hello, world!

function greet() {
  console.log("Hello, world!");
}

greet = "Not a function"; // Overrides the function
Enter fullscreen mode Exit fullscreen mode

7. Best Practices

  1. Declare Variables at the Top: Always declare variables at the beginning of their scope.
   let age;
   age = 25;
Enter fullscreen mode Exit fullscreen mode
  1. Use let and const: Avoid var to reduce unexpected behaviors caused by hoisting.
   const name = "Alice";
   let age = 30;
Enter fullscreen mode Exit fullscreen mode
  1. Define Functions Before Usage: Write function declarations before calling them for better readability.
   function sayHello() {
     console.log("Hello!");
   }

   sayHello();
Enter fullscreen mode Exit fullscreen mode
  1. Be Aware of Temporal Dead Zone (TDZ): Initialize let and const variables only after their declaration.

8. Summary

  • Hoisting lifts declarations (variables, functions, classes) to the top of their scope.
  • var is initialized to undefined, while let and const remain uninitialized.
  • Function declarations are hoisted with their definitions, but function expressions and arrow functions are not.
  • Always structure your code with clear declarations and initializations to avoid confusion caused by hoisting.

Hi, I'm Abhay Singh Kathayat!
I am a full-stack developer with expertise in both front-end and back-end technologies. I work with a variety of programming languages and frameworks to build efficient, scalable, and user-friendly applications.
Feel free to reach out to me at my business email: kaashshorts28@gmail.com.

Top comments (0)