const
(Constant Variables)In JavaScript, const
is used to declare constants, meaning the variable cannot be reassigned after being initialized. However, properties of objects and elements of arrays declared with const
can still be modified.
const
const variableName = value;
const
→ Declares the variable as a constant.variableName
→ The name of the constant variable.value
→ The initial value (must be assigned during declaration).
const
Once a value is assigned to a const
variable, it cannot be changed.
const PI = 3.14;
PI = 3.14159; // ❌ Error: Assignment to constant variable
Unlike let
or var
, reassigning a const
variable will cause an error.
You must assign a value when declaring a const
variable; otherwise, an error occurs.
const x; // ❌ Error: Missing initializer in const declaration
This is different from let
and var
, which allow declaration without initialization.
const
has block-level scope, meaning it exists only inside the {}
block where it is defined.
if (true) {
const a = 10;
}
console.log(a); // ❌ Error: a is not defined
It does not leak outside the block, similar to let
.
Although const
prevents reassigning the variable itself, it does not prevent modifying properties of objects or changing elements in an array.
const person = { name: "Alice", age: 25 };
person.age = 26; // ✅ Allowed
console.log(person.age); // Output: 26
Here, we are not reassigning person
, just modifying one of its properties.
const numbers = [1, 2, 3];
numbers.push(4); // ✅ Allowed
console.log(numbers); // Output: [1, 2, 3, 4]
We can modify an array's elements but cannot reassign the entire array:
numbers = [5, 6, 7]; // ❌ Error: Assignment to constant variable
const
?✔ Use const
when the variable should never be reassigned after its initial declaration.
✔ Best for constants, objects, and arrays that don’t need reassignment.
✔ Improves code clarity and prevents accidental changes.
🔹 Conclusion
const
prevents reassignment but allows modification of objects and arrays.const
by default unless you need reassignment (then use let
).@asadmukhtar