JavaScript ยท Chapter 7 of 55

JavaScript Variables (let, const, var)

Variables store data values. Modern JavaScript offers three ways to declare them: `var` (old, function-scoped), `let` (block-scoped, reassignable), and `const` (block-scoped, cannot be reassigned).

Today, best practice is to use `const` by default and `let` only when a value needs to change. Avoid `var` in new code because of its confusing scoping rules.

let vs const

`let` allows reassignment: `let x = 1; x = 2;`. `const` locks the binding: attempting to reassign throws an error, though objects/arrays declared with const can still be mutated internally.

var's pitfalls

`var` is function-scoped, not block-scoped, so it can leak out of if-blocks and loops, causing subtle bugs. It is also hoisted with an initial value of `undefined`.

Example 1 (javascript)
let age = 25;
age = 26;
console.log(age);
Output
26

let allows reassignment.

Example 2 (javascript)
const PI = 3.14159;
console.log(PI);
Output
3.14159

const values cannot be reassigned after declaration.

Key points

  • Use `const` by default, `let` when reassignment is needed.
  • Avoid `var` โ€” it is function-scoped and hoisted confusingly.
  • `const` prevents reassignment, not mutation of objects/arrays.
  • Variables must be declared before use in strict mode.
๐Ÿ’ก Note: Reassigning a `const` throws 'TypeError: Assignment to constant variable.'

๐Ÿ“ Quick Quiz

1. Which declaration cannot be reassigned?

2. Which keyword is function-scoped rather than block-scoped?

3. What is the modern best-practice default?