
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.
- Constants (
β 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).