let, const & var
How JavaScript declares variables — scope, hoisting, and when to use each
Knowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
JavaScript has three ways to declare variables: var, let, and const.
var — function-scoped, hoisted (declaration moved to top of function), can be re-declared. Avoid in modern code.
let — block-scoped (lives only inside {}), not hoisted into usable state, can be reassigned but not re-declared in the same scope.
const — block-scoped like let, but the binding cannot be reassigned. Objects/arrays declared with const can still be mutated.
var x = 1; // function scope, avoid
let y = 2; // block scope, reassignable
const z = 3; // block scope, can't reassign bindingThe hoisting trap with var:
javascript console.log(a); // undefined (not ReferenceError) var a = 5; // var declarations are "hoisted" to the top of their function — // the name exists but has no value until the assignment runs.
Rule of thumb: Default to const. Use let when you need to reassign. Never use var.
Examples
Block scope with let
let and const are confined to the block; var escapes
if (true) {
let x = 10;
const y = 20;
var z = 30;
}
// console.log(x); // ReferenceError — let is block-scoped
// console.log(y); // ReferenceError — const is block-scoped
console.log(z); // 30 — var leaks out of the blockconst with objects
const prevents reassignment, not mutation
const user = { name: 'Alice' };
user.name = 'Bob'; // OK — mutating the object
// user = {}; // TypeError — can't reassign the binding
console.log(user.name); // 'Bob'Next in JavaScript Core
Arrow Functions