Variables declared by const must not change their values. Why is it possible that the value has changed?

const scrollTop = document.documentElement.scrollTop
scroll bar event, drag the scroll bar to print the scrollTop with different values each time! Didn"t you say the value can"t be changed? Why is this okay?

Es6
May.07,2022

if you just define it in the function, because the function has scope, that is, when the function is executed, the variable will be automatically destroyed, and when it is called again, the variable will be defined again, so the value has changed not because of modification, but because of redefinition.
of course, if it is an object, the


my understanding is that the
document.documentElement.scrollTop exists in a memory address, even though it is a const definition. The variable declared by
const points to this address, and the value of the address has changed, but the pointer to const has not changed.


this actually involves primitive type and reference type
const defines a constant, and the value of a constant cannot be modified

.

primitive type

take string among the six primitive types as an example

const a = '1';
a = '2'; // => 

reference type

take object among the three reference types as an example

const a = {b: 1};
a.b = 2; // => 
a = 2; // => 

reason

  • the operation on the primitive type is to manipulate the value itself.
  • is not allowed in the constant.
  • the operation on an attribute in the reference type actually has no effect on the value itself
  • in the above example, modifying a.b is actually a modification to b. But it has no effect on a
Menu