Skip to content

Latest commit

 

History

History
109 lines (78 loc) · 2.97 KB

File metadata and controls

109 lines (78 loc) · 2.97 KB

Hoisting in JavaScript (Variable & Function)

What is Hoisting?

In JavaScript, hoisting is the behavior where variable and function declarations are moved to the top of their scope (before code execution) during the creation phase of the execution context.

Important: Only declarations are hoisted, not initializations.

Hoisting with Variables

var

  • Hoisted and initialized to undefined.
  • Can be accessed before declaration, but value will be undefined until the line where it's assigned.
console.log(a); // undefined
var a = 10;
console.log(a); // 10

Behind the scenes:

var a; // Hoisted declaration
console.log(a);
a = 10;
console.log(a);

let and const

  • Hoisted but not initialized.
  • Placed in the Temporal Dead Zone (TDZ) from the start of the block until the declaration line.
  • Accessing before declaration → ReferenceError.
console.log(b); // ReferenceError
let b = 20;

console.log(c); // ReferenceError
const c = 30;

Hoisting with Functions

Function Declarations

  • Hoisted with the entire function definition.
  • Can be called before their declaration.
greet(); // "Hello"
function greet() {
  console.log('Hello');
}

Behind the scenes:

function greet() {
  console.log('Hello');
}
greet();

Function Expressions

Behavior depends on whether you use var, let, or const.

Using var:

  • Hoisted, but initialized to undefined.
  • Calling before assignment → TypeError (because undefined is not a function).
sayHi(); // TypeError: sayHi is not a function
var sayHi = function () {
  console.log('Hi');
};

Using let or const:

  • Hoisted but in TDZ.
  • Calling before declaration → ReferenceError.
sayHi(); // ReferenceError
let sayHi = function () {
  console.log('Hi');
};

Hoisting Summary Table

Declaration Type Hoisted? Initialized? Access Before Decl.
var Yes undefined ✅ undefined
let Yes No (TDZ) ❌ ReferenceError
const Yes No (TDZ) ❌ ReferenceError
Function Declaration (Statement) Yes Yes (full fn) ✅ Works
Function Expression (var) Yes undefined ❌ TypeError
Function Expression (let/const) Yes No (TDZ) ❌ ReferenceError

Interview Soundbite:

"In JavaScript, hoisting moves variable and function declarations to the top of their scope during the creation phase. Variables declared with var are initialized to undefined, while let and const are hoisted but not initialized, causing a Temporal Dead Zone until declaration. Function declarations are fully hoisted with their definitions, whereas function expressions follow variable hoisting rules."