const is used to declare constant bindings — variables whose identifier cannot be reassigned, but whose contents may still change (if it’s an object or array).

1. What const does — simple definition

  • Creates a block-scoped variable
  • Must be initialized at declaration time
  • The binding cannot be reassigned
  • Works perfectly with objects and arrays (the object can change, but the variable name cannot be reassigned)

Example:

const PI = 3.14159;

2. Basic Syntax

const variableName = value;

THIS is NOT allowed:

const x; // SyntaxError: Missing initializer

3. Block Scope

const obeys block scope exactly like let.

{
const a = 10;
console.log(a); // 10
}
console.log(a); // ReferenceError

4. Constants cannot be reassigned

const score = 100;
score = 200; // TypeError: Assignment to constant variable

Even redeclaring is not allowed:

const score = 100;
const score = 200; // SyntaxError

5. BUT Arrays and Objects declared with const can be modified

const prevents reassignment, NOT mutation.

Example with Array:

const numbers = [1, 2, 3];
numbers.push(4);        // OK
numbers[0] = 10;        // OKnumbers = [100, 200]; // NOT OK (reassignment)

Example with Object:

const user = { name: "Zaman", age: 25 };

user.age = 26; // OK
user.country = "BD"; // OK

user = {}; // ❌ NOT OK

6. Use const by default

Modern JS style guides (like Airbnb, Google) suggest:

Use const by default, use let only when you need reassignment.

Good:

const user = getUser();

Only use let when necessary:

let counter = 0;
counter++;

7. const with loops

Not allowed (reassigning)

for (const i = 0; i < 5; i++) {
console.log(i); // TypeError
}

✔ Allowed (for-of or for-in)

No reassignment happens in each iteration — each cycle gets a new binding.

for (const item of [10, 20, 30]) {
console.log(item);
}

8. Practical real-world examples

Example 1: Using const for DOM elements

const button = document.querySelector("#submitBtn");
button.addEventListener("click", handleSubmit);

Example 2: Using const for configuration

const TAX_RATE = 0.15;
const USD_RATE = 111.5;

Example 3: Storing arrow functions

const add = (a, b) => a + b;
console.log(add(2, 3));

Categorized in:

Javascript ES6,