The const
keyword in JavaScript is used to declare constant variables. These variables cannot be reassigned once they are defined, making them ideal for values that should remain constant throughout the program.
Syntax of const
const variableName = value;
const
: The keyword to declare a constant variable.variableName
: The name of the constant variable.value
: The value assigned to the variable (required).
Features of const
Block Scopeconst
variables are confined to the block in which they are declared.
Example:
{
const pi = 3.14;
console.log(pi); // Outputs: 3.14
}
console.log(pi); // Error: pi is not defined
No Reassignment
You cannot reassign a new value to a const
variable after it has been declared.
Example:
const name = "Junaid";
name = "Arsheen"; // Error: Assignment to constant variable
Must Be Initializedconst
variables must be initialized at the time of declaration.
Example:
const age; // Error: Missing initializer in const declaration
Works with Objects and Arrays
While you cannot reassign an object or array declared with const
, you can modify their contents.
Example:
const person = { name: "Junaid" };
person.age = 29; // Adding a new property is allowed
console.log(person); // Outputs: { name: "Junaid", age: 29}
const numbers = [1, 2, 3];
numbers.push(4); // Modifying the array is allowed
console.log(numbers); // Outputs: [1, 2, 3, 4]
Difference Between const
, let
, and var
Feature | const | let | var |
---|---|---|---|
Scope | Block scope | Block scope | Function or global scope |
Reassignment | Not allowed | Allowed | Allowed |
Redeclaration | Not allowed | Not allowed | Allowed |
Initialization | Mandatory at the time of declaration | Optional | Optional |
Modification | Allowed for objects and arrays | Allowed | Allowed |
The const
keyword is an essential tool in JavaScript for declaring immutable variables. It enhances code reliability, reduces errors, and is especially useful for objects and arrays. By understanding and leveraging const
, you can write cleaner, more maintainable code.