Home Web Front-end Front-end Q&A How to declare read-only constants in es6

How to declare read-only constants in es6

Jan 11, 2023 pm 05:38 PM
es6 constant

In es6, you can use the const keyword to declare read-only constants, the syntax is "const constant name = constant value;"; once declared, the constant must be initialized and the initialized value cannot be changed. Constants declared by const belong to the block scope and are subject to the "temporary dead zone". They will not create any global properties on the window and cannot be reassigned or redeclared.

How to declare read-only constants in es6

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

In es6, you can use the const keyword to declare read-only constants.

es6 const keyword

const declares a read-only constant. Once declared, a constant must be initialized and the initialized value cannot be changed.

const PI = 3.1415;
PI // 3.1415

PI = 3;
// TypeError: Assignment to constant variable.
Copy after login

const constants comply with the following rules:

  • belongs to the block scope.

  • is subject to the "temporary dead zone".

  • It does not create any global properties on window.

  • Not reassignable.

  • Cannot be redeclared.

const Once a variable is declared, it must be initialized immediately.

const foo;
// SyntaxError: Missing initializer in const declaration
Copy after login

The above code indicates that for const, if you just declare without assigning a value, an error will be reported.

The scope of const is the same as that of the let command: it is only valid within the block-level scope where it is declared.

if (true) {
  const MAX = 5;
}

MAX // Uncaught ReferenceError: MAX is not defined
Copy after login

The constants declared by the const command are not promoted. There is also a temporary dead zone and can only be used after the declared position.

if (true) {
  console.log(MAX); // ReferenceError
  const MAX = 5;
}
Copy after login

The above code is called before the constant MAX is declared, and an error is reported.

Constant declared by const cannot be declared repeatedly like let.

var message = "Hello!";
let age = 25;

// 以下两行都会报错
const message = "Goodbye!";
const age = 30;
Copy after login

The essence of const

What const actually guarantees is not that the value of the variable cannot be changed, but that the data stored in the memory address pointed to by the variable cannot be changed. For simple types of data (numeric values, strings, Boolean values), the value is stored at the memory address pointed to by the variable, and is therefore equivalent to a constant. But for composite type data (mainly objects and arrays), the memory address pointed to by the variable only stores a pointer to the actual data. Const can only guarantee that this pointer is fixed (that is, it always points to another fixed address) , as for whether the data structure it points to is variable, it is completely out of control. Therefore, you must be very careful when declaring an object as a constant.

const foo = {};

// 为 foo 添加一个属性,可以成功
foo.prop = 123;
foo.prop // 123

// 将 foo 指向另一个对象,就会报错
foo = {}; // TypeError: "foo" is read-only
Copy after login

In the above code, the constant foo stores an address, which points to an object. What is immutable is only this address, that is, foo cannot be pointed to another address, but the object itself is mutable, so new properties can still be added to it.

Here is another example.

const a = [];
a.push('Hello'); // 可执行
a.length = 0;    // 可执行
a = ['Dave'];    // 报错
Copy after login

In the above code, the constant a is an array. The array itself is writable, but if another array is assigned to a, an error will be reported.

If you really want to freeze the object, you should use the Object.freeze method.

const foo = Object.freeze({});

// 常规模式时,下面一行不起作用;
// 严格模式时,该行会报错
foo.prop = 123;
Copy after login

In the above code, the constant foo points to a frozen object, so adding new attributes will not work, and an error will be reported in strict mode.

In addition to freezing the object itself, the properties of the object should also be frozen. Below is a function that completely freezes an object.

var constantize = (obj) => {
  Object.freeze(obj);
  Object.keys(obj).forEach( (key, i) => {
    if ( typeof obj[key] === 'object' ) {
      constantize( obj[key] );
    }
  });
};
Copy after login

【Related recommendations: javascript video tutorial, programming video

The above is the detailed content of How to declare read-only constants in es6. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot Article

Hot Article

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are constants in C language? Can you give an example? What are constants in C language? Can you give an example? Aug 28, 2023 pm 10:45 PM

What are constants in C language? Can you give an example?

How to create a constant in Python? How to create a constant in Python? Aug 29, 2023 pm 05:17 PM

How to create a constant in Python?

Is async for es6 or es7? Is async for es6 or es7? Jan 29, 2023 pm 05:36 PM

Is async for es6 or es7?

How to find different items in two arrays in es6 How to find different items in two arrays in es6 Nov 01, 2022 pm 06:07 PM

How to find different items in two arrays in es6

In Java, is it possible to define a constant using only the final keyword? In Java, is it possible to define a constant using only the final keyword? Sep 20, 2023 pm 04:17 PM

In Java, is it possible to define a constant using only the final keyword?

Why does the mini program need to convert es6 to es5? Why does the mini program need to convert es6 to es5? Nov 21, 2022 pm 06:15 PM

Why does the mini program need to convert es6 to es5?

Is es6 map ordered? Is es6 map ordered? Nov 03, 2022 pm 07:05 PM

Is es6 map ordered?

What does es6 temporary Zenless Zone Zero mean? What does es6 temporary Zenless Zone Zero mean? Jan 03, 2023 pm 03:56 PM

What does es6 temporary Zenless Zone Zero mean?

See all articles