The role and usage of const in JavaScript
JavaScript is a programming language widely used in web development. Its flexibility and dynamics are one of its characteristics. . In JavaScript, we can use the const keyword to declare a constant. This article will introduce the role and usage of the const keyword, and provide some specific code examples to help readers better understand.
The following are some uses of const Specific examples of keywords:
//Declare a constant
const PI = 3.14;
//The value of a constant cannot be changed
PI = 3.1415926; // Error: Constant The value cannot be changed
// Initialization is required when declaring a constant
const age; // SyntaxError: Initialization is required when declaring a constant
// Constants declared by const need to be assigned a value when declaring
const name = "Alice";
name = "Bob"; // Error: The value of the constant cannot be changed
The following are some code examples to demonstrate the characteristics of the const keyword:
// Example 1: Block-level scope
{
const name = "Alice" ;
console.log(name); // Output: Alice
}
console.log(name); // ReferenceError: name is not defined
// Example 2: Constant Same name as the variable
const name = "Alice";
let name = "Bob"; // SyntaxError: Identifier 'name' has already been declared
// Example 3: Constant declaration promotion
console.log(name); // Output: undefined
const name = "Alice";
Summary: The
const keyword is used to declare an unchangeable constant. Using the const keyword can improve the readability and robustness of the code and avoid accidental variable modifications. Constants have block-level scope and cannot be modified once assigned. However, it should be noted that constants declared as const must be assigned a value when declared, and cannot have the same name as variables and functions with the same name. I hope this article can help readers better understand and use the const keyword in JavaScript.
The above is the detailed content of The usage and function of JavaScript const keyword. For more information, please follow other related articles on the PHP Chinese website!