In JavaScript, const is a keyword introduced in ECMAScript 6 (ES6) that allows developers to declare variables that are block-scoped constants. Once a variable is declared with const and assigned a value, that value cannot be reassigned or changed. Here's how const is used:
You use const to declare a variable and assign an initial value. Once assigned, the value cannot be changed.
const PI = 3.14;
const name = "John";
Like let, variables declared with const are block-scoped. They are only accessible within the block they are defined in.
Example:
{
const x = 10;
console.log(x); // Output: 10
}
// x is not accessible here
console.log(x); // Uncaught ReferenceError: x is not defined
Unlike variables declared with let, variables declared with const cannot be reassigned. Trying to reassign a const variable will result in an error.
Example:
const count = 5;
count = 10; // Error: Assignment to constant variable
When using const, you must initialize the variable with a value at the time of declaration. Otherwise, you'll get an error.
Example:
const x; // SyntaxError: Missing initializer in const declaration
x = 5;
Variables declared with const are not truly immutable, but their values are read-only. This means that if a const variable holds an object or array, you can still modify the properties or elements of that object or array. However, you cannot reassign the variable itself.
Example:
const person = {
name: "John",
age: 30
};
person.age = 31; // Valid, modifies the object
person = { name: "Jane", age: 25 }; // Error: Assignment to constant variable
Example Usage:
Here's an example demonstrating the usage of `const`:
const gravity = 9.81; // Declaring a constant
if (gravity > 9.8) {
const message = "High gravity"; // Scoped to this block
console.log(message); // Output: High gravity
}
// message is not accessible here
console.log(message); // Uncaught ReferenceError: message is not defined
Notes:
const is used to declare variables that are read-only constants. It ensures that the value of the variable does not change throughout the program, providing predictability and safety. Understanding how const works is important for writing robust and maintainable JavaScript code.