JavaScript Hoisting Explained: var, let, and Function Declarations

What is Hoisting in JavaScript? Hoisting is JavaScript's default behavior of moving variable and function declarations to the top of their scope before execution. This means you can sometimes use variables or functions before they are declared in the code. 1️⃣ Variable Hoisting with var console.log(a); // undefined var a = 10; Behind the scenes, JavaScript interprets it like this: var a; console.log(a); // undefined a = 10; 👉 The declaration is hoisted, but not the assignment. 2️⃣ Hoisting with let and const console.log(a); // ❌ ReferenceError let a = 10; Variables declared with let and const are hoisted but placed in the Temporal Dead Zone (TDZ), meaning they cannot be accessed before initialization. 3️⃣ Function Hoisting Function declarations are fully hoisted. greet(); function greet() { console.log("Hello JavaScript"); } This works because the entire function definition is hoisted. #javascript #webdevelopment #frontenddeveloper #mernstack #codinginterview #softwareengineering

To view or add a comment, sign in

Explore content categories