Constants in es6 cannot be modified; constants in es are declared using const. The constants declared by this keyword are read-only. Once declared, they cannot be modified; because const constants guarantee that the value cannot be modified, guaranteed The data stored in the memory address pointed to by the constant cannot be changed, while the value of the basic data type constant is stored in the memory address.
The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.
Definition of const: It is a read-only constant. Once declared, it cannot be modified
Yes Really can't be modified? Type a few pieces of code to take a look
As you can see from the picture above, after const defines the string constant, try to modify it, and the error 'Assignment to constant variable' is reported. Type a few pieces of code again. Take a look
It can be seen from the above several pieces of code that when the constant defined by const is a 'basic data type', it cannot be Modification; when the defined constant is a 'reference data type', we can modify the data through its properties
Why is this so?
Because const constants guarantee that the value cannot be changed, what is actually guaranteed is that the data stored in the memory address pointed to by the constant cannot be modified:
The value of the 'basic data type' is stored in the memory address. , so the 'basic data type' defined by const cannot be changed.
The memory address pointed to by 'reference data type' is just a pointer, which points to the actual data. In other words, it is the pointer that cannot be changed, not the data, so the "reference data type" defined by const ' constants can modify their values through attributes. This involves pop-up memory and heap memory.
As can be seen from the figure, the basic data types The variables and values are all in 'stack memory', and the memory address pointed to cannot be modified
Variables of reference data types are stored in 'stack memory', and values are stored in 'heap memory' ', the corresponding value in the 'heap memory' is pointed to by a pointer. Therefore, the reference data type defined by const cannot be changed by the 'pointer', so the value can be modified through attributes.
【Related recommendations: javascript video tutorial, web front-end】
The above is the detailed content of Can constants be modified in es6?. For more information, please follow other related articles on the PHP Chinese website!