Hoisting helps you understand how JavaScript moves some code parts before running. It explains why you can use some things before you write them.
0
0
What hoisting is in Javascript
Introduction
When you want to know why a variable or function works even if declared later in the code.
When debugging errors about variables or functions not found.
When learning how JavaScript reads your code step by step.
When writing functions and variables to avoid unexpected behavior.
When explaining to others why some code runs without errors even if order looks wrong.
Syntax
Javascript
// Variables and functions are 'hoisted' to the top console.log(name); // undefined var name = 'Alice'; sayHi(); function sayHi() { console.log('Hi!'); }
Only declarations are hoisted, not initializations.
Function declarations are fully hoisted, variables declared with var are hoisted but not their values.
Examples
The variable
age is hoisted but its value is not, so it prints undefined.Javascript
console.log(age); // undefined var age = 25;
The function
greet is hoisted completely, so it can be called before its definition.Javascript
greet(); function greet() { console.log('Hello!'); }
Variables declared with
let are hoisted but are in a temporal dead zone until initialized, so this causes a ReferenceError.Javascript
console.log(city); // ReferenceError let city = 'Paris';
Sample Program
This program shows how var variables are hoisted with undefined value, and functions are fully hoisted.
Javascript
console.log(message); // What will this print? var message = 'Hello, world!'; sayHello(); function sayHello() { console.log('Hello from function!'); }
OutputSuccess
Important Notes
Hoisting only moves declarations, not assignments.
Use let and const to avoid confusion from hoisting.
Function expressions are not hoisted like function declarations.
Summary
Hoisting means JavaScript moves declarations to the top before running code.
Variables declared with var are hoisted but start as undefined.
Functions declared with function are fully hoisted and can be called before they appear.