Detailed explanation of the usage of const in JavaScript
In JavaScript, const is a keyword used to define constants. Unlike var and let, variables defined by const cannot be changed. Once a constant is defined, it cannot be assigned a value. This article will explain in detail how to use const and give specific code examples.
const PI = 3.14;
PI = 3.14159; // Error! The constant PI cannot be modified
In the above code, we define a constant named PI and assign it a value of 3.14. We then tried to change the value of PI to 3.14159 again, but this was wrong because constants declared as const cannot be modified.
{
const a = 10;
console.log(a); // Output 10
}
console.log(a ); // Error! Variable a is undefined
In the above code, we declare a constant a via const inside a code block and assign it a value of 10. We can access the value of a inside the code block and print it out, but accessing a outside the code block will cause an error because a is only visible inside the code block.
const person = {
name: 'Alice',
age: 20
};
person.age = 21; // OK Modify the properties of the object
person = {}; // Error! The constant person cannot be reassigned
In the above code, we declare a constant person using const and assign it to an object. Although the constant person cannot be reassigned, we can modify the properties in the person object because the object itself is mutable.
const numbers = [1, 2, 3, 4, 5];
numbers.push(6); // Elements can be added to the array
numbers[0] = 0; //You can modify the elements in the array
In the above code, we use const to declare a constant numbers and assign it to an array. Even though numbers is a constant, we can still change the contents of the array by adding elements and modifying elements.
const fruits = ['apple', 'banana', 'orange'];
fruits[0] = 'pear'; // You can modify the elements in the array
In the above code, we use const to declare a constant fruits, whose value is an array. Although we can modify the elements in the fruits array, we cannot point fruits to a different memory address.
Summary:
Use the const keyword It allows us to better manage constants and prevent accidental modifications in programming. Although constants declared as const can modify their properties and elements, they cannot be reassigned. Reasonable use of the const keyword can improve the readability and maintainability of the code.
The above is a detailed analysis of the usage and precautions of the const keyword in JavaScript. I hope it will be helpful to readers.
The above is the detailed content of A closer look at the JavaScript const keyword. For more information, please follow other related articles on the PHP Chinese website!