← JavaScript

Fundamentals

What is the difference between `var`, `let` and `const`?

Show answer — try answering out loud first

var is function-scoped and can be redeclared; let and const are block-scoped. let can be reassigned, const cannot. Today the recommendation is to use const by default and reach for let only when you need to reassign.

  • var: the old way. It is scoped to the entire function where it is declared (it ignores blocks like if or for). It also undergoes hoisting and is initialized to undefined.
  • let: block-scoped ({ }). You can change its value, but you cannot redeclare it in the same block.
  • const: also block-scoped. You cannot reassign it. Be careful: if it holds an object or an array, its contents can indeed be modified; what cannot change is the reference.

Rule of thumb: always use const; switch to let only if you really need to reassign; avoid var.

const nombre = "Mike";
// nombre = "Otro"; // Error: a const cannot be reassigned

let edad = 25;
edad = 26; // OK: let can be reassigned

// const with an object: the reference does not change, but the contents do
const usuario = { activo: true };
usuario.activo = false; // OK
console.log(usuario); // { activo: false }

// Block scope
if (true) {
  var conVar = "visible afuera";
  let conLet = "solo aquí adentro";
}
console.log(conVar); // "visible afuera"
// console.log(conLet); // Error: conLet is not defined

Thinking that const makes the value "immutable". It does not: const only prevents reassigning the variable. An object or array declared with const can freely mutate its contents.

"var is function-scoped and is avoided nowadays. let and const are block-scoped. The difference between them is that let can be reassigned and const cannot. I use const by default and only switch to let when I need to reassign the value. An important point: const does not make an object immutable, it only prevents changing the reference."

Quick challenge

What does this code print and why?

for (var i = 0; i < 3; i++) {}
console.log(i);
See answer

It prints 3. Since var is function-scoped (not block-scoped), the variable i still exists after the for loop and keeps its last value.