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.
Variable hoisting behavior in 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.
undefined because var x is hoisted and initialized as undefined before assignment.console.log(x); var x = 5;
let y is hoisted but not initialized, so it cannot be accessed before declaration.console.log(y); let y = 10;
var a is hoisted, so console.log(a) prints undefined.function test() { console.log(a); var a = 3; } test();
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.
console.log(message); var message = 'Hello!'; try { console.log(greeting); } catch (e) { console.log('Error:', e.message); } let greeting = 'Hi!';
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.
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.