Lesson 4 / 38

Variables: let, const, var

Three ways to declare, and why const should be your default.

Declaring variables

let can be reassigned, const cannot, and var is the old, function-scoped way.

let age = 25;
age = 26;          // OK

const name = "Ada";
// name = "Bo";    // TypeError

var legacy = "old style";

Block vs function scope

let/const are block-scoped — confined to { }. var is function-scoped and leaks out of blocks like if or for.

Default to const

Use const unless you know the value will change, then reach for let. Avoid var in modern code.

const with objects

const locks the binding, not the contents — an object or array declared with const can still be mutated.

const user = { name: "Ada" };
user.name = "Grace";   // allowed
console.log(user);

Output:

{ name: 'Grace' }