-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
In JavaScript, hoisting is a behavior in which variable and function declarations are moved to the top of their containing scope during the compilation phase. This means that you can use variables and functions before they are explicitly declared in the code. Understanding hoisting is crucial for avoiding unexpected results, writing cleaner code, and debugging effectively.
In this tutorial, you will learn about JavaScript hoisting, how it works with variables and functions, practical examples, common mistakes, best practices, and real-world applications.
Hoisting is important because it:
Explains why certain code works even if variables or functions are declared later
Helps prevent reference errors in some cases
Clarifies the behavior of var, let, and const declarations
Allows function declarations to be used before they appear in the code
Helps developers understand execution context and memory allocation
Without a clear understanding of hoisting, developers may encounter confusing behavior in their programs, particularly with variable shadowing and function calls.
During the compilation phase, JavaScript scans the code for variable and function declarations. It then moves these declarations to the top of their scope. Importantly:
Function declarations are hoisted completely, meaning both the function name and body are moved to the top.
Variables declared with var are hoisted but initialized with undefined.
Variables declared with let and const are hoisted but are in a temporal dead zone until their declaration is reached. Accessing them before declaration results in a ReferenceError.
varconsole.log(name); // undefined
var name = "Aarushi";
console.log(name); // Aarushi
Explanation:
During compilation, JavaScript hoists the var name declaration to the top.
The variable is initially undefined.
When the assignment name = "Aarushi" occurs, the value is updated.
let and constconsole.log(age); // ReferenceError
let age = 25;
console.log(score); // ReferenceError
const score = 90;
Variables declared with let or const cannot be accessed before their declaration due to the temporal dead zone.
Function declarations are fully hoisted, allowing you to call the function before it appears in the code.
greet();
function greet() {
console.log("Hello, Priya!");
}
Output:
Hello, Priya!
Function expressions are treated like variables. If assigned to var, let, or const, only the variable is hoisted, not the function body.
sayHello(); // TypeError: sayHello is not a function
var sayHello = function() {
console.log("Hi, Saanvi!");
};
With var, the variable sayHello is hoisted but initialized as undefined. Calling it before assignment results in a TypeError. With let or const, accessing it before declaration results in a ReferenceError.
var Before Declarationconsole.log(course); // undefined
var course = "JavaScript";
console.log(course); // JavaScript
calculate();
function calculate() {
console.log("Calculation done!");
}
The function can be invoked before its declaration because the function declaration is hoisted entirely.
console.log(getScore); // undefined
var getScore = function() {
console.log("Score calculated!");
};
getScore(); // Score calculated!
console.log(player); // ReferenceError
let player = "Aarushi";
console.log(level); // ReferenceError
const level = 5;
Accessing these variables before declaration causes a runtime error.
function outer() {
inner();
function inner() {
console.log("Inner function executed");
}
}
outer(); // Inner function executed
Nested function declarations are hoisted within their parent function scope.
Expecting let and const variables to behave like var
Calling function expressions before assignment
Assuming hoisting affects only functions, not variables
Using variables before initialization, leading to undefined or errors
Confusing the temporal dead zone with undefined values
Always declare variables at the top of their scope to improve readability
Use let and const for block-scoped variables to avoid unintended hoisting issues
Declare functions before calling them if using function expressions
Keep nested functions simple and predictable
Understand hoisting behavior to prevent subtle bugs
Structuring code in a readable and predictable manner
Debugging reference errors and undefined variables
Writing modular code with proper variable and function placement
Ensuring asynchronous code works correctly when using function expressions
Avoiding global variable pollution and conflicts
JavaScript hoisting is a mechanism where variable and function declarations are moved to the top of their containing scope. Function declarations are fully hoisted, while var variables are hoisted but initialized with undefined. Variables declared with let and const are hoisted but remain in a temporal dead zone until their declaration. Understanding hoisting helps developers write cleaner, bug-free code, avoid common pitfalls, and make better decisions regarding variable and function declarations.
Access a var variable before its declaration and log its value. Explain the output.
Access a let variable before its declaration and observe the result. Explain why it differs from var.
Call a function declared with a function declaration before its definition and log the output.
Call a function assigned to a function expression using var before its assignment. Explain the error.
Call a function assigned to a function expression using let before its assignment. Explain the result.
Inside a function, access a var variable before declaration and observe the output.
Inside a function, access a let or const variable before declaration and explain the Temporal Dead Zone.
Demonstrate variable hoisting by declaring multiple var variables in different blocks and accessing them outside the blocks.
Write a function that uses a var counter variable and a nested function. Access the counter before initialization and after increment.
Compare hoisting behavior of var, let, and const by creating variables of each type in the global scope and trying to access them before declaration.
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
