JavaScript Const
JavaScript const
The const keyword in JavaScript is used to declare variables that are intended to be immutable, meaning their values cannot be changed after they are assigned. Introduced in ECMAScript 6 (ES6), const is block-scoped, similar to let, and helps to maintain consistency in your code.
1. Constant Declaration
The const keyword declares a variable with a constant value. The value assigned to a const variable cannot be changed after initialization. However, if the constant is an object or an array, the contents of the object or array can still be modified.
Constant Declaration Example
const pi = 3.14159;
console.log(pi); // Outputs: 3.14159
// pi = 3.14; // Error: Assignment to constant variable
In this example, attempting to reassign a new value to pi will result in an error because pi is declared with const.
2. Constant Arrays and Objects
Although you cannot reassign a new array or object to a const variable, you can still modify the contents of the array or object.
Constant Arrays Example
const numbers = [1, 2, 3];
numbers.push(4); // Valid: Modifies the contents of the array
console.log(numbers); // Outputs: [1, 2, 3, 4]
// numbers = [5, 6, 7]; // Error: Assignment to constant variable
In this example, you can modify the array numbers by adding new elements, but you cannot reassign a new array to numbers.
Constant Objects Example
const person = { name: 'John', age: 30 };
person.age = 31; // Valid: Modifies the contents of the object
console.log(person); // Outputs: { name: 'John', age: 31 }
// person = { name: 'Jane', age: 25 }; // Error: Assignment to constant variable
In this example, you can change the properties of the object person, but you cannot reassign a new object to person.
3. Block Scope
The const keyword creates a block-scoped variable. This means the variable is only accessible within the block in which it is declared.
Block Scope Example
// Block Scope
{
const blockScopedConst = 'I am block-scoped';
console.log(blockScopedConst); // Accessible here
}
console.log(blockScopedConst); // Error: blockScopedConst is not defined
In this example, blockScopedConst is only accessible within the block where it is declared, and trying to access it outside the block results in an error.