Immutable vs Mutable
Mutable is a type of variable that can be changed. In JavaScript, only objects and arrays are mutable, not primitive values.
A mutable object is an object whose state can be modified after it is created.
Immutables are the objects whose state cannot be changed once the object is created.
요약
Mutable
- 메모리 상에서 할당된 값을 변환할 수 있는 것
- 해당 데이터 주소를 찾아서 값을 반환
Immutable
- 메모리에 할당된 값을 변환할 수 없는 것 ( 값은 재할당 가능 )
- 해당 데이터 주소와 별개의 새로운 주소에 값이 할당
설명
자바스크립트 에는 크게 2가지 Data Type이 존재함.
1. Primitive Data Type ( Value Type )
- Numbers
- Boolean
- String
- Null
- Undefined
- Symbol
2. Non-Primitive Data Type ( Reference Type )
- Array
- Object
- Function
- Date
- Regex
Primitive Data Type
- Immutable
Ex.) String
// String 값의 hasCode (주소값)을 반환 하는 Function
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var str1 = 'temp';
console.log('str1: ', str1.hashCode(), ` assigned: ${str1}`);
해당 구문이 실행되면 문자열 'temp'가 메모리에 생성되고, 식별자 str1 은 'temp'의 메모리 주소를 가리킨다.
결과:
그리고 2번째 코드 실행
str1 = 'temp2';
console.log('str1 with temp2: ', str1.hashCode(), ` assigned: ${str1}`);
2번째 구문이 실행되면 이전에 메모리에 저장되어 있던 'temp'를 수정하는 것이 아니라 새로 문자열 'temp2'를 새로운 메모리 주소에 생성한다.
그리고 식별자는 'temp'를 가리킨다.
결과:
보다시피 다른 hascode ( 다른 reference 주소 )가 확인이 된다.
이때 문자열 'temp'와 'temp2'는 지속적으로 메모리에 존재 하지만 추후에 Garbage Collector가 안 쓰는 것은 처리해준다.
그럼 만약에 아래에 코드처럼 똑같은 문자열에 서로 다른 두 식별자가 참조하면 어떻게 될까?
var p1 = '1';
console.log('p1: ', p1.hashCode(), ` assigned: ${p1}`);
var p2 = '1';
console.log('p2: ', p2.hashCode(), ` assigned: ${p2}`);
console.log('p1 과 p2 는 같은가? ', p1 === p2);
한번 메모리에 Assign 된 문자열은 계속 존재하므로, 새로 생성되는 식별자가 메모리에 이미 존재하는 문자열을 참조한다면 결국 다른 ( 기존에 생성된) 식별자와 같은 곳을 가리키게 된다.
코드 결과
Non-Primitive Data Type
- Mutable
Ex.) Array
위 문자열 예제와 동일하게 서로 다른 두 식별자에게 동일 한 값을 assign 하고, 이후에 한 식별자의 값만 변경하도록 해보겠다.
var arr1 = [1, 2, 3, 4];
var arr2 = [1, 2, 3, 4];
console.log('arr1: ', arr1);
console.log('arr2: ', arr2);
console.log('arr1 과 arr2 는 같은 가 ? ', arr1 === arr2);
Immutable ( ex. 문자열 ) 개념이라면, arr1, arr2는 같은 메모리 값 [1, 2, 3, 4]를 가리키고 있을 것이다.
그러므로 서로 같은 값을 참조한다며 3번째 console.log 에 true를 반환할 텐데,
우선 결과 값을 한번 확인해보자.
Immutable 값과 다르게 mutable 값은 false를 리턴한다. 왜 일까?
arr1, arr2 식별자는 각각 동일한 값을 가지고 있지만, 배열은 한번 메모리에 할당되면, 다른 식별자가 같은 값을 가지고 있더라도 해당 메모리를 참조할 수 없기 때문에 ( Immutable ), 같은 값이 라도 새로운 메모리에 할당이 되어야 한다. 때문에 arr1, arr2 서로 다른 메모리를 참조하기 때문에 FALSE를 리턴.
Ref
https://developer.mozilla.org/en-US/docs/Glossary/Mutable#see_also
Mutable - MDN Web Docs Glossary: Definitions of Web-related terms | MDN
Mutable is a type of variable that can be changed. In JavaScript, only objects and arrays are mutable, not primitive values.
developer.mozilla.org
https://blog.devgenius.io/mutable-and-immutable-in-javascript-78a3cbc6187c
Mutable and immutable in JavaScript
By the definition of Mozilla -
blog.devgenius.io
'FrontEnd > Javascript' 카테고리의 다른 글
async vs defer in HTML script tags (0) | 2023.09.19 |
---|---|
document.referrer 구현 (0) | 2023.01.26 |