??What is Hoisting in JavaScript | Hoisting Functions, Variables and Classes

??What is Hoisting in JavaScript | Hoisting Functions, Variables and Classes

Hoisting is a fundamental concept in JavaScript where function, variable, or class declarations are moved to the top of their scope during the compilation phase (before the code execution). This behavior allows you to use functions or variables before they are declared in the code.

However, only declarations are hoisted, not initializations or assignments. Let’s dive deep into how hoisting works for functions, variables, and classes.

Function Hoisting

In JavaScript, function declarations are fully hoisted. This means you can call a function even before it’s declared in the code.


Key Points:

  1. Function Declarations: Fully hoisted, allowing you to call the function before the declaration.
  2. Function Expressions: Only the variable gets hoisted, not the function itself.

Variable Hoisting

Variable declarations using var, let, and const behave differently when hoisted:

  1. var: Variables declared with var are hoisted to the top of their scope but initialized with undefined.
  2. let and const: These are hoisted but not initialized. Accessing them before the declaration results in a ReferenceError due to the Temporal Dead Zone (TDZ).

Class Hoisting

Classes in JavaScript are also hoisted, but they are not initialized. Accessing a class before its declaration will result in a ReferenceError.


Got questions or examples where hoisting surprised you? Let’s discuss below! ?? #JavaScript #CodingTips #WebDevelopment

Satyam Kumar

Frontend Web Developer || React || JavaScript ||Tailwind CSS || Responsive Web design || CSS || HTML || C || C++ || Python || Data Science

3 个月

Useful tips

要查看或添加评论,请登录

Sonu Kumar的更多文章