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

  1. Choose const for values that should not be rebound: javascript const PI = 3.14159; const user = { name: 'Ava' };
  2. Choose let for counters and reassignable state: javascript let count = 0; count += 1;
  3. Avoid var because it is function-scoped and hoisted, which can cause unexpected behavior.

Tips

  • const prevents 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 var inside loops with callbacks often captures the final value due to function scope.
  • Reassigning a const throws a TypeError.
  • Temporal dead zone means you cannot access let/const before their declaration.