I would like to ask, why are these two ways of writing const wrong?

problem description

I found two ways to write const on the Internet. why is one reporting an error while the other is successful?

clipboard.png

Jul.12,2022
Reference type variables such as

arrays store addresses, and the address points that are equivalent to directly changing the variable are the same concept as you directly reassign variables. So it will be wrong.
the following changes the elements in the array. In essence, the memory address stored by names has not changed, so it will not report an error


MDN explanation: The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g.its properties) can be altered.

The concrete explanation of

is that the variable is assigned to a specific memory address after the link is compiled, and the value of the variable is the content stored at that address. Initializing a variable with const assigns the initial variable value to the specified memory address. At this point, the memory address has been determined to be unchangeable, and then the assignment will assign the variable to another address and report an error, while the value of the variable stored in the address can be modified.


const declares constants, which cannot be assigned, that is, when you const name = [] In the case of , the value of this name can only be [] , and can no longer be assigned to [1 to 2 const name 3] . If you do need a constant, you can const name = [1 to 2 hr class= 3]


const statement will prevent the modification of the variable binding to the variable itself. This means that the const declaration does not prevent modifications to variable members


the first is to assign a value to name with an array, and const declares constants.


const declaration creates a read-only reference to a value. However, this does not mean that the value it holds is immutable, but the variable identifier cannot be reassigned. For example, in the case where the reference content is an object, this means that you can change the content of the object (for example, its parameters).


const is a constant and can only be assigned when declaring

.
Menu