Let’s go through const in JavaScript in detail.


πŸ”Ή const in JavaScript

The const keyword is used to declare constants in JavaScript.
πŸ‘‰ Introduced in ES6 (2015), just like let.


1️⃣ Syntax

const variableName = value;

Example:

const PI = 3.14159;
const name = "Raj";

2️⃣ Features of const

βœ… Block Scope

  • Just like let, const is block-scoped.
{
  const x = 10;
  console.log(x); // 10
}
// console.log(x); ❌ Error (not accessible outside block)

❌ Cannot Redeclare or Reassign

  • You cannot redeclare or reassign a const variable.
const city = "Delhi";
// city = "Mumbai"; ❌ Error: Assignment to constant variable
// const city = "Pune"; ❌ Error: Already declared
console.log(city); // Delhi

βœ… Must Be Initialized

  • You must assign a value when declaring a const.
// const x; ❌ Error: Missing initializer
const x = 50; // βœ… Correct

βœ… Hoisting with TDZ

  • Like let, const is hoisted but exists in the Temporal Dead Zone (TDZ) until declared.
  • Accessing it before declaration throws an error.
// console.log(a); ❌ ReferenceError
const a = 10;

βœ… Objects & Arrays with const

  • Important: const makes the binding (variable reference) constant, not the actual value inside objects/arrays.
  • You can modify contents of objects/arrays declared with const.
// Array Example
const numbers = [1, 2, 3];
numbers.push(4); // βœ… Allowed
console.log(numbers); // [1, 2, 3, 4]
// numbers = [5, 6]; ❌ Error (cannot reassign whole array)

// Object Example
const person = { name: "Raj", age: 20 };
person.age = 21; // βœ… Allowed
console.log(person); // {name: "Raj", age: 21}
// person = { name: "Kumar" }; ❌ Error (cannot reassign object)

3️⃣ When to Use const?

  • When you know a value should never change.
  • Good for:
    • Constants (PI, tax rates, app settings).
    • Arrays/objects whose reference shouldn’t change.

βœ… Summary

  • Block-scoped (like let).
  • Must be initialized when declared.
  • ❌ Cannot redeclare or reassign.
  • βœ… Can modify objects/arrays (but not reassign them).
  • Preferred by default in modern JS (use let only if reassignment is needed).

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *