Programing

자바 스크립트에서 상수 값을 변경할 수있는 이유

lottogame 2020. 10. 14. 07:19
반응형

자바 스크립트에서 상수 값을 변경할 수있는 이유


ES6가 아직 표준화되지 않았다는 것을 알고 있지만 현재 많은 브라우저 const 가 JS에서 키워드를 지원 합니다.

사양에서 다음과 같이 작성되었습니다.

상수 값은 재 할당을 통해 변경할 수 없으며 상수를 다시 선언 할 수 없습니다. 이 때문에 상수를 초기화하지 않고 선언 할 수 있지만 그렇게하는 것은 쓸모가 없습니다.

그리고 이렇게하면 :

const xxx = 6;
xxx = 999;
xxx++;
const yyy = [];
yyy = 'string';
yyy = [15, 'a'];

나는 모든 것이 괜찮 볼 xxx여전히 6하고 yyy있다 [].

그러나 그렇게 yyy.push(6); yyy.push(1);하면 내 상수 배열이 변경되었습니다. 지금 [6, 1]은 그렇고 나는 아직도 그것을 바꿀 수 없습니다 yyy = 1;.

이건 버그인가요, 아니면 뭔가 빠졌나요? 나는 최신 크롬과 FF29에서 그것을 시도했다


문서는 다음과 같이 설명합니다.

... 상수는 재 할당을 통해 변경할 수 없습니다
... 상수는 다시 선언 할 수 없습니다.

배열이나 객체에 추가 할 때 상수를 재 할당하거나 다시 선언하지 않고 이미 선언하고 할당 한 것이며 상수가 가리키는 "목록"에 추가하는 것입니다.

따라서 이것은 잘 작동합니다.

const x = {};

x.foo = 'bar';

console.log(x); // {foo : 'bar'}

x.foo = 'bar2';

console.log(x); // {foo : 'bar2'}  

이:

const y = [];

y.push('foo');

console.log(y); // ['foo']

y.unshift("foo2");

console.log(y); // ['foo2', 'foo']

y.pop();

console.log(y); // ['foo2']

하지만 둘 다 :

const x = {};
x = {foo: 'bar'}; // error - re-assigning

const y = ['foo'];
const y = ['bar']; // error - re-declaring

const foo = 'bar'; 
foo = 'bar2';       // error - can not re-assign
var foo = 'bar3';   // error - already declared
function foo() {};  // error - already declared

이것은 상수가 실제로 배열에 대한 참조저장하기 때문에 발생합니다 . 배열에 무언가를 결합 할 때 상수 값을 수정하는 것이 아니라 가리키는 배열을 수정하는 것입니다. 객체를 상수에 할당하고 그 속성을 수정하려는 경우에도 마찬가지입니다.

수정할 수 없도록 배열 또는 개체를 고정하려면 Object.freeze이미 ECMAScript 5의 일부인 메서드를 사용할 수 있습니다 .

const x = Object.freeze(['a'])
x.push('b')
console.log(x) // ["a"]

This is consistent behavior with every programming language I can think of.

Consider C - arrays are just glorified pointers. A constant array only means that the value of the pointer will not change - but in fact the data contained at that address is free to.

In javascript, you are allowed to call methods of constant objects (of course - otherwise constant objects would not serve much purpose!) These methods might have the side effect of modifying the object. Since arrays in javascript are objects, this behavior applies to them as well.

All you are assured of is that the constant will always point to the same object. The properties of the object itself are free to change.


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 parameters) can be altered.

In addition, an also important note:

Global constants do not become properties of the window object ...

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const


I think this would give you more clarity on the issue : https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0 .

Basically it boils down to the const always pointing to the same address in memory. You can change the value stored in that address but cannot change the address the const is pointing too.

The definition of const you mentioned will hold true when the const is pointing to an address that holds a primitive value . This is because you cannot assign a value to this const without changing its address (because this is how assigning primitive values work) and changing the address of a const is not allowed.

Where as if the const is pointing to non-primitive value , it is possible to edit the value of the address.


Came through this article while searching on why I was able to update an Object even after defining it as const. So the point here is that it is not the Object directly but the attributes it contains which can be updated.

For example, my Object looks like:

const number = {
    id:5,
    name:'Bob'
};

The above answers correctly pointed out that it's the Object which is const and not its attribute. Hence, I will be able to update the id or name by doing:

number.name = 'John';

But, I will not be able to update the Object itself like:

number = {
    id:5,
    name:'John'
  };

TypeError: Assignment to constant variable.

참고URL : https://stackoverflow.com/questions/23436437/why-can-i-change-value-of-a-constant-in-javascript

반응형