The 'const' keyword in JavaScript is used to declare variables that are meant to be constant and cannot be reassigned. Here are some key points about the 'const' keyword:
1. Immutable Bindings: When a variable is declared with 'const', it cannot be reassigned a different value. This does not mean that the value itself is immutable. For example, if the value is an object or an array, the properties of the object or the elements of the array can still be modified.
const x = 10;
x = 20; // This will cause an error
const obj = { a: 1 };
obj.a = 2; // This is allowed, the object itself is mutable
2. Block Scope: Variables declared with 'const' have block scope, which means they are only accessible within the block where they are declared. A block is defined by a pair of curly braces '{}'.
if (true) {
const y = 5;
console.log(y); // 5
}
console.log(y); // This will cause an error, y is not defined
3. Declaration and Initialization: A 'const' variable must be initialized at the time of declaration. It cannot be declared without initialization.
const z; // This will cause an error
const z = 15; // This is correct
4. Reference Type Mutability: As mentioned earlier, if a 'const' variable holds a reference to an object or array, the reference cannot be changed, but the contents of the object or array can be modified.
const arr = [1, 2, 3];
arr.push(4); // This is allowed
console.log(arr); // [1, 2, 3, 4]
arr = [5, 6, 7]; // This will cause an error
5. Temporal Dead Zone (TDZ): Like 'let', 'const' has a temporal dead zone, which means the variable cannot be accessed before its declaration in the code.
console.log(a); // This will cause a ReferenceError
const a = 3;
Using 'const' is beneficial because it makes your code more predictable by ensuring that variables intended to remain constant do not get reassigned accidentally. However, it is important to understand that 'const' does not make the value itself immutable if it is a reference type like an object or array. To achieve full immutability, you can use methods such as 'Object.freeze' for objects.
No comments:
Post a Comment