Understanding the const Keyword in JavaScript

Learn how the const keyword works in JavaScript, when to use it, and how it differs from let and var. This post covers common mistakes, best practices, and examples to help you write more predictable, bug-resistant code using const.

Evans Samson

8 juin 2025

Understanding the const Keyword in JavaScript

Photo by James Harrison on Unsplash

What is const?

const is a keyword introduced in ES6 (ECMAScript 2015) that allows you to declare block-scoped constants — variables that cannot be reassigned after they’re initialized.

const name = "Alice";
name = "Bob"; // ❌ TypeError: Assignment to constant variable

🔹 Key Characteristics of const

  1. Must be initialized at declaration You must assign a value when declaring a const.

    const city = "New York"; // ✅
    const state; // ❌ SyntaxError
    
  2. 🚫 Cannot be reassigned Once declared, the variable binding cannot be changed.

    const age = 30;
    age = 35; // ❌ Error
    
  3. 🧠 Does NOT make objects/arrays immutable You can still change the contents of a const object or array — but not reassign the variable itself.

    const person = { name: "Alice" };
    person.name = "Bob"; // ✅ Allowed
    person = {}; // ❌ Error
    

🔹 const vs let vs var

Feature

const

let

var

Scope

Block

Block

Function

Hoisting

No (TDZ)

No (TDZ)

Yes

Reassignable

❌ No

✅ Yes

✅ Yes

Redeclarable

❌ No

❌ No

✅ Yes

🔸 TDZ = Temporal Dead Zone (can't access before declaration)


🔹 When to Use const

Use const by default unless you know the value will change. This encourages immutable code, which helps prevent bugs and makes your code easier to reason about.

✅ Best for:

  • Configuration values

  • Fixed references (functions, objects)

  • Preventing accidental reassignment


🔹 Real-Life Example

const API_KEY = "abc123";
const user = {
  name: "Jane",
  loggedIn: true
};

// Modify object properties
user.loggedIn = false; // ✅

🔚 Conclusion

Using const in JavaScript is a great way to write clearer, more predictable code. It doesn’t make values immutable — but it does lock the variable’s reference, which is incredibly useful for maintaining consistency in your applications.

Pro Tip: Start with const, use let only when you know reassignment is needed. Avoid var in modern codebases.


Commentaires

Inscrivez-vous à notre newsletter