Lessons in this course (16)

2. var, let and const; scope and hoisting

Basic★ Must knowLesson 2 of 16
varletconst
ScopeFunctionBlock {}Block
HoistedYes, initialised to undefinedYes, but in the Temporal Dead Zone until declaredSame as let
Re-declareAllowedNot allowedNot allowed
Re-assignYesYesNo (but object contents can change)
Global object propertyYes (window.x)NoNo
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.