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 likeiforfor). It also undergoes hoisting and is initialized toundefined.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.
"
varis function-scoped and is avoided nowadays.letandconstare block-scoped. The difference between them is thatletcan be reassigned andconstcannot. I useconstby default and only switch toletwhen I need to reassign the value. An important point:constdoes not make an object immutable, it only prevents changing the reference."
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.