0
0
Javascriptprogramming~5 mins

Variable hoisting behavior in Javascript

Choose your learning style9 modes available
Introduction

Variable hoisting means JavaScript moves variable declarations to the top before running code. This helps avoid errors when variables are used before they are declared.

When you want to understand why a variable can be used before its declaration without error.
When debugging unexpected undefined values in your code.
When learning how JavaScript handles variable declarations inside functions or blocks.
When deciding between var, let, and const for declaring variables.
When reading or maintaining older JavaScript code that uses var.
Syntax
Javascript
var variableName;
let variableName;
const variableName = value;

var declarations are hoisted and initialized with undefined.

let and const declarations are hoisted but not initialized, causing a 'temporal dead zone' until their declaration line.

Examples
This prints undefined because var x is hoisted and initialized as undefined before assignment.
Javascript
console.log(x);
var x = 5;
This causes a ReferenceError because let y is hoisted but not initialized, so it cannot be accessed before declaration.
Javascript
console.log(y);
let y = 10;
Inside the function, var a is hoisted, so console.log(a) prints undefined.
Javascript
function test() {
  console.log(a);
  var a = 3;
}
test();
Sample Program

This program shows how var and let behave differently with hoisting. The var variable prints undefined before assignment. The let variable causes an error if accessed before declaration.

Javascript
console.log(message);
var message = 'Hello!';

try {
  console.log(greeting);
} catch (e) {
  console.log('Error:', e.message);
}

let greeting = 'Hi!';
OutputSuccess
Important Notes

Always declare variables at the top of their scope to avoid confusion.

Prefer let and const over var to prevent bugs related to hoisting.

Functions are also hoisted, but their behavior differs from variables.

Summary

JavaScript moves variable declarations to the top before running code.

var variables are hoisted and initialized as undefined.

let and const are hoisted but not initialized, causing errors if accessed early.