Home >Web Front-end >JS Tutorial >Usage of const in js

Usage of const in js

下次还敢
下次还敢Original
2024-05-01 04:27:14639browse

In JavaScript, const is used to declare constant variables whose values ​​cannot be reassigned while the program is running. Purposes include: 1) preventing variables from being reassigned; 2) identifying immutable constants. The syntax is: const variableName = value.

Usage of const in js

Usage of const in JavaScript

In JavaScript, the const keyword is used Declare constant variables. The value of a constant variable cannot be reassigned while the program is running.

Main purpose

  • Prevent variable reassignment: Using const to declare variables can prevent accidental changes, thus Improve code robustness.
  • Identifying constants: Values ​​declared using const typically represent immutable constants, such as mathematical constants (e, π) or application configuration options.

Syntax

<code class="javascript">const variableName = value;</code>

Where:

  • variableName:To be declared The name of the constant variable.
  • value: The value to be assigned to the constant.

Note

  • Constant variables must be initialized when declared.
  • The value of a constant variable cannot be reassigned.
  • Constant variables cannot be declared as objects or arrays, but constant variables can be assigned to objects or arrays.
  • Constant variables are usually named with all uppercase letters to indicate their constant nature.

Example

<code class="javascript">// 声明一个数学常数
const PI = 3.14159;

// 声明一个应用程序配置选项
const APPLICATION_NAME = "My Application";

// 声明一个不可变对象
const person = {
  name: "John Doe",
  age: 30
};</code>

In the above example, PI, APPLICATION_NAME and person are constant variables, and their values ​​cannot be modified while the program is running.

The above is the detailed content of Usage of const in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to use includes in jsNext article:How to use includes in js