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`.
let age = 25;
age = 26;
console.log(age);26let allows reassignment.
const PI = 3.14159;
console.log(PI);3.14159const 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.
