희락코딩

JavaScript _tip / MUTABLE과 IMMUTABLE 구분하자!! 본문

프로그래밍/자바스크립트 꿀팁 개념

JavaScript _tip / MUTABLE과 IMMUTABLE 구분하자!!

Hello JoyCoding 2021. 4. 21. 01:56
728x90
반응형

MUTABLE과 IMMUTABLE 구분


코딩 공부를 하면서 mutable 과 immutable이라는 개념을 본적있습니다. 이개념들이 너무 생소하고 어렵게 느껴져서 최대한 쉽게 정리해 이해 할 수 있도록 정리하였습니다.

 

mutable과 immutable 의 차이점


▶ mutable

→  변하다 유동적이다.

→  참조타입

→  해당 데이터 주소를 찾아 값을 변경

 

 

▶ immutable

→  불변, 변하지 않는다.

→  원시타입

→  해당 데이터 주소와 별개로 새로운 메모리 주소에 할당

→  문자열

 

우선   mutable 과 immutable 의 차이를 나타내는 키워드입니다.  

 

가장 핵심적인 것은 mutable원본데이터를 변화 시키려는 속성이 있고 immutable원본데이터를 유지하려는 속성이 있습니다.

 

String Method - immutable


문자열 메서드는 전부 immutable이라고 생각하면 됩니다.

 

// ex
   String.slice()
   String.replace()
   String.split()
  .
  .
  .

 

Array Method - immutable or mutable


Array Method는 메서드 별로 달라서 자주 사용하는 것만 알아 두면 좋습니다.

간단한 예시를 통해 immutablemutable이 차이를 알아보겠습니다.

 

1
2
3
4
5
6
7
8
// Arry.concat() - immutable
let arr1 = [1,2,3]
let arr2 = [4,5]
let concatArr = arr1.concat(arr2);
 
concatArr; // [1,2,3,4,5]
arr1; // [1,2,3]
arr2; // [4,5]
cs

 

concat()메서드는 배열을 합쳐주는 메서드입니다. concat()은 immutable여서 원본을 유지합니다.

 

그렇다면 원본이 바뀌는 Array.pop()메서드를 활용하여 살펴 보겠습니다. 

 

1
2
3
4
5
6
// Arry.prp() - mutable             
let arr = [1,2,3,4]
 
arr.pop() // 4
arr; // [1,2,3]
 
cs

 

pop()메서드는 배열의 마지막 요소를 삭제 시켜주는 메서드 입니다. pop()은 mutable이여서 원본을 수정합니다.

 

※ 예시를 통해 immutable  mutable 의 차이점을 직관적으로 확인할수 있습니다. 쉽게 말해 원본 데이터 변화 유무를 확인하면 됩니다.

 

 

▶ 자주 쓰이는 immutable & mutable메서드 정리

 

mutable

Array.pop()
Array.push()
Array.unshift()
Array.shift()
Array.splice()
Array.fill()
Array.reverse()
Array.sort()
.

.
.

immutable

Array.concat()
Array.filter()
Array.find()
Array.forEach()
Array.includes()
Array.indexOf()
Array.map()
Array.join()
.

.
.

 

참고자료

https://doesitmutate.xyz/

 

Does it mutate?

The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex.Array.prototype.lastIndexOf ( searchElement [ , fromIndex ] )

doesitmutate.xyz

 

728x90
반응형
Comments