Hoisting is how JavaScript moves some declarations to the top before running code. Knowing common hoisting pitfalls helps avoid bugs where variables or functions seem to act strangely.
Common hoisting pitfalls in Javascript
// var declarations are hoisted console.log(x); // undefined var x = 5; // function declarations are hoisted foo(); // works function foo() { console.log('hello'); } // let and const are hoisted but not initialized console.log(y); // ReferenceError let y = 10;
Only declarations are hoisted, not initializations.
var variables are hoisted and initialized with undefined.
console.log(a); // undefined var a = 3;
foo(); function foo() { console.log('Hi'); }
console.log(b); // ReferenceError let b = 4;
bar(); var bar = function() { console.log('Hey'); };
This program shows different hoisting behaviors: var x is hoisted and initialized as undefined, so first log prints undefined. Accessing let y before declaration causes ReferenceError. Function foo() is hoisted fully so calling it before declaration works. Calling bar() before assignment causes TypeError because bar is undefined at that time.
console.log(x); // undefined var x = 1; console.log(y); // ReferenceError let y = 2; foo(); // works function foo() { console.log('foo called'); } bar(); // TypeError var bar = function() { console.log('bar called'); };
var declarations are hoisted and initialized with undefined, so you can access them before assignment but get undefined.
let and const are hoisted but not initialized, causing a 'temporal dead zone' error if accessed early.
Function declarations are hoisted completely, but function expressions are not hoisted as functions.
var declarations are hoisted and initialized with undefined.
let and const are hoisted but accessing them before declaration causes errors.
Function declarations are fully hoisted, function expressions are not.