Beginner freeCodeCamp • introduction-to-javascript

How Do let and const Work Differently When It Comes to Variable Declaration, Assignment, and Reassignment?

Lesson Overview

Choosing between `let` and `const` is one of the most important decisions you make when writing modern JavaScript.

Choosing between let and const is one of the most important decisions you make when writing modern JavaScript.

let: The Reassignable Variable

Use let when you know the value of the variable will change later in the program.

let score = 0;
score = 10; // Reassignment is allowed

const: The Constant

Use const (short for “constant”) when the value should stay the same. Once you assign a value to a const, you cannot reassign it.

const birthYear = 1995;
birthYear = 1996; // ❌ Uncaught TypeError: Assignment to constant variable.

Key Differences

Featureletconst
Reassignment✅ Allowed❌ Not Allowed
InitializationOptional✅ Mandatory (must assign a value immediately)
ScopeBlock ScopeBlock Scope

Best Practices

  1. Default to const: Use const for everything unless you are certain the value needs to change. This makes your code more predictable and prevents accidental bugs.
  2. Use let for loops: Since loop counters (like i) change with each iteration, they must be declared with let.
  3. Avoid var: var is the old way of doing things and can lead to confusing bugs due to how it handles “scope.”