Roadmap › JavaScript (ES5 → ES2025) & TypeScript Basics › Module: Language Basics
Lessons in this course (16)
2. var, let and const; scope and hoisting
Basic★ Must knowLesson 2 of 16
var | let | const | |
|---|---|---|---|
| Scope | Function | Block {} | Block |
| Hoisted | Yes, initialised to undefined | Yes, but in the Temporal Dead Zone until declared | Same as let |
| Re-declare | Allowed | Not allowed | Not allowed |
| Re-assign | Yes | Yes | No (but object contents can change) |
| Global object property | Yes (window.x) | No | No |
js
console.log(a); // undefined (hoisted var)
var a = 1;
console.log(b); // ReferenceError: Cannot access 'b' before initialization (TDZ)
let b = 2;
const user = { name: "Asha" };
user.name = "Ravi"; // allowed — the binding is constant, not the object
// user = {}; // TypeError
Object.freeze(user); // shallow immutability
sayHi(); // works — function declarations are fully hoisted
function sayHi() { console.log("hi"); }
// sayBye(); // TypeError — function expressions follow variable rules
var sayBye = function () {};Scopes: global, function, block, module. Lexical scoping: a function's scope is determined by where it is written, not where it is called.