JavaScript constants, declared using the const
keyword (introduced in ES6), are variables whose values cannot be reassigned after initialization. They provide a mechanism to ensure data integrity and prevent accidental modifications.
Declaring Constants:
The syntax for declaring a constant is straightforward:
JavaScript
const constantName = value;
constantName
: Choose a meaningful name that reflects the constant's purpose.value
: The initial value assigned to the constant.
Key Points:
Initialization is Mandatory: You must assign a value to a constant during its declaration.
Immutable Reference: While you can't reassign the constant itself, you can modify the contents of arrays or objects referenced by a constant (explained later).
Example:
JavaScript
const PI = 3.14159;
const MAX_VALUE = 100;
console.log("PI:", PI); // Output: PI: 3.14159
Block Scope:
Like let
, constants have block scope. This means they are only accessible within the code block where they are declared (e.g., if
statement, loop, or function body).
JavaScript
{
const x = "John";
}
// x is not accessible here
Redeclaration and Reassignment:
Redeclaration: You cannot redeclare a constant with the same name within the same block.
Reassignment: Once assigned, a constant's value cannot be changed using the assignment operator (
=
).
Constant Arrays and Objects:
While you cannot reassign the reference of a constant array or object, you can modify their contents:
JavaScript
const fruits = ["apple", "banana", "orange"];
fruits[0] = "mango"; // Update element at index 0
fruits.push("grape"); // Add element to the end
console.log(fruits); // Output: ["mango", "banana", "orange", "grape"]
Constant vs. Let:
Feature | const | let |
Scope | Block scope | Block scope |
Redeclaration | Not allowed in the same block | Not allowed in the same block |
Reassignment | Not allowed | Allowed |
Hoisting | No | No |
Best Practices:
Use
const
by default for variables that should remain constant throughout your program.Choose clear and descriptive names for constants.
If you need to modify the contents of a collection (array or object), consider using
let
to declare the variable referencing the collection.
By effectively using constants, you can write more reliable and predictable JavaScript code.