let / const
Try it yourself →Defines variables; const does not change.
Syntax
let name = value; const constant = value;
Description
You define variables that can be changed later with let, and unchanging (constant) variables with const. Default choice is const; use let only if it will change.
Returns
—
Example
let counter = 0; counter = 1; const pi = 3.14; console.log(counter, pi);
Expected output
1 3.14
When to use?
Storing all kinds of data. const makes code safer (prevents accidental changes).
Common mistakes
- ⚠️ Reassigning to a const throws an error (TypeError).
- ⚠️ Using a variable before defining it throws an error.