Can const change data in JavaScript?

Is it the first reaction of many people, no, const cannot be defined repeatedly, and the value cannot be modified. But is it true?

Then let's make an example to see

// 定义常量 MY_FAV 并赋值 7
const MY_FAV = 7;

// 报错 - Uncaught TypeError: Assignment to constant variable.
MY_FAV = 20;

Run Google Chrome to see the result

 You can see that the console is reporting an error, and we cannot assign values ​​to constant variables again. This is the same as what we usually say, but is it really the case?

Let's take another example

const MY_OBJECT = {'key': 'value'};

// 重写对象和上面一样会失败
// Uncaught TypeError: Assignment to constant variable.
MY_OBJECT = {'OTHER_KEY': 'value'};

Take a look at the browser console

 Does this explain the problem? The description cannot be modified? So can we try to rewrite the value of the attribute?

const MY_OBJECT = {'key': 'value'};

// 对象属性并不在保护的范围内
// 下面这个声明会成功执行
MY_OBJECT.key = 'otherValue'; // Use Object.freeze() to make object immutable
console.log(MY_OBJECT)

 The value of the property of this object we defined was changed! ! ! ! !

How about changing it to an array?

//定义一个新数组
const MY_ARRAY = [];

// 向数组填充,删除数据,查看一下数组的变化
MY_ARRAY.push('A'); // ["A"]
console.log(MY_ARRAY)
MY_ARRAY.pop()
console.log(MY_ARRAY)

Print the result on the console to see

After filling and deleting values, the values ​​in the array can be changed 

However, let's try to reassign it?

 Still reporting an error that cannot assign a value to a constant variable

What is the reason? ? ? ?

Looking at the above example, it is not difficult for us to find out. When const defines the value of the basic type, if we modify it directly through assignment, it is obviously impossible. But if const defines a reference type, we can do it by modifying the value of the property. If we go to assign some other operation, we can't modify it.

The conclusion is:

The basic types of JavaScript (boolean, number, string) cannot be modified

JavaScript reference types (objects, arrays) can modify their property values

Guess you like

Origin blog.csdn.net/zsusanj/article/details/129729876