Javascript 简明教程

JavaScript - Constants

JavaScript Constants

JavaScript constants 是在程序执行过程中其值保持不变的变量。您可以使用 const 关键字声明常量。

JavaScript constants are the variables whose values remain unchanged throughout the execution of the program. You can declare constants using the const keyword.

const 关键字在 JavaScript 的 ES6 版本中引入,与 let 关键字一起使用。const 关键字用于定义具有 constant reference 的变量。用 const 定义的变量不能 redeclaredreassigned 。const 声明具有块和函数范围。

The const keyword is introduced in the ES6 version of JavaScript with the let keyword. The const keyword is used to define the variables having constant reference. A variable defined with const can’t be redeclared, reassigned. The const declaration have block as well as function scope.

Declaring JavaScript Constants

如果使用 const 关键字声明变量,则始终需要在声明时分配一个值。

You always need to assign a value at the time of declaration if the variable is declared using the const keyword.

const x = 10; // Correct Way

在任何情况下,都不能不初始化而使用 const 关键字声明变量。

In any case, you can’t declare the variables with the const keyword without initialization.

const y; // Incorrect way
y = 20;

Can’t be Reassigned

不能更新用 const 关键字声明的变量的值。

You can’t update the value of the variables declared with the const keyword.

const y = 20;
y = 40; // This is not possible

Block Scope

使用 const 关键字声明的 JavaScript 变量具有块级作用域。这意味着在块级作用域外,它被视为不同的变量。

A JavaScript variable declared with const keyword has block-scope. This means same variable is treated as different outside the blcok.

在以下示例中,在块级作用域内声明的 x 与在块级作用域外声明的 x 不同。因此,可以在块级作用域外 redeclare 同一个变量。

In the below example, the x declared within block is different from x declared outside the blcok. So we can redeclare the same variable outsite the block

{
const x = "john";
}
const x = "Doe"

但在同一个块级作用域内 can’t redeclare const 变量。

But we can’t redeclare the const varaible within the same block.

{
const x = "john";
const x = "Doe" // incorrect
}

Constant Arrays and Objects in JavaScript

可以使用 const 关键字声明数组和对象,但在数组和对象声明中有一点小技巧。

We can declare the arrays and objects using the const keyword, but there is a little twist in the array and object declaration.

使用 const 关键字的变量保持常量引用,而不是常量值。因此,您可以更新使用 const 关键字声明的同一数组或对象,但不能将新数组或对象的引用重新分配给该常量变量。

The variable with the const keyword keeps the constant reference but not the constant value. So, you can update the same array or object declared with the const keyword, but you can’t reassign the reference of the new array or object to the constant variable.

Example (Constant Arrays)

在以下示例中,我们使用 const 关键字定义名为“arr”的数组。之后,我们更新数组中第一个元素并插入“fence”字符串作为数组的末尾元素。

In the example below, we have defined the array named 'arr' using the const keyword. After that, we update the array element at the 0th index and insert the 'fence' string at the end of the array.

在输出中,您可以看到它打印了更新后的数组。

In the output, you can observe that it prints the updated array.

<html>
<head>
   <title> Consant Arrays </title>
</head>
<body>
   <script>
      // Defining the constant array
      const arr = ["door", "window", "roof", "wall"];
      // Updating arr[0]
      arr[0] = "gate";
      // Inserting an element to the array
      arr.push("fence");
	  //arr = ["table", "chair"] // reassiging array will cause error.
      // Printing the array
      document.write(arr);
   </script>
</body>
</html>

执行以上代码时,将会产生以下结果 −

When you execute the above code, it will produce the following result −

gate,window,roof,wall,fence

Example (Constant Objects)

在以下示例中,我们用 const 关键字创建“obj”对象。接下来,我们更新对象的“animal”属性并在对象中插入“legs”属性。在输出中,代码将会打印已更新的对象。

In the below example, we created the 'obj' object with the const keyword. Next, we update the 'animal' property of the object and insert the 'legs' property in the object. In the output, the code prints the updated object.

<html>
<head>
   <title> Constant Objects </title>
</head>
<body>
   <script>
      // Defining the constant object
      const obj = {
         animal: "Lion",
         color: "Yellow",
      };
      // Changing animal name
      obj.animal = "Tiger";
      // Inserting legs property
      obj.legs = 4;
      // Printing the object
      document.write(JSON.stringify(obj));
      // obj = { name: "cow" } // This is not possible
   </script>
</body>
</html>

它将产生以下结果 −

It will produce the following result −

{"animal":"Tiger","color":"Yellow","legs":4}

No Const Hoisting

用 const 关键字定义的变量不会提升到代码顶部。

Varaibles defined with const keyword are not hoisted at the top of the code.

在下面的示例中,在定义 const 变量 x 之前就对其进行了访问。它将导致一个错误。我们可以使用 try-catch 语句捕获该错误。

In the example below, the const variable x is accessed before it defined. It will cause an error. We can catch the error using try-catch statement.

<html>
<body>
   <script>
      document.write(x);
	  const x = 10;
   </script>
</body>
</html>

以下是使用 const 关键字声明的变量的一些其他属性。

Here are some other properties of the variables declared with the const keyword.

  1. Block scope.

  2. It can’t be redeclared in the same scope.

  3. Variables declared with the const keyword can’t be hoisted at the top of the code.

  4. Constant variables value is a primitive value.

Difference between var, let and const

我们给出了使用 var、let 和 const 关键字声明的变量之间的比较表。

We have given the comparison table between the variables declared with the var, let, and const keywords.

Comparison basis

var

let

const

Scope

Function

Block

Block

Hoisted

Yes

No

No

Reassign

Yes

Yes

No

Redeclare

Yes

No

No

Bind This

Yes

No

No

Which should you use among var, let, and const?

  1. For the block scope, you should use the let keyword.

  2. If you need to assign the constant reference to any value, use the const keyword.

  3. When you require to define the variable inside any particular block, like a loop, 'if statement', etc. and need to access outside the block but inside the function, you may use the var keyword.

  4. However, you can use any keyword to define global variables.

  5. Redeclaring variables is not a good practice. So, you should avoid it, but if necessary, you may use the var keyword.