How to declare variables in JavaScript using let, const, and var
· Category: JavaScript
Short answer
Use const by default, let when reassignment is needed, and avoid var in modern code. Each keyword defines a variable with different scoping and mutability rules.
Steps
- Choose
constfor values that should not be rebound:javascript const PI = 3.14159; const user = { name: 'Ava' }; - Choose
letfor counters and reassignable state:javascript let count = 0; count += 1; - Avoid
varbecause it is function-scoped and hoisted, which can cause unexpected behavior.
Tips
constprevents rebinding, not mutation; object properties can still change.- Declare variables at the top of their block to improve readability.
- Use destructuring to declare multiple related variables concisely.
Common issues
- Using
varinside loops with callbacks often captures the final value due to function scope. - Reassigning a
constthrows aTypeError. - Temporal dead zone means you cannot access
let/constbefore their declaration.