[JS] primitive value & reference value

뿌야·2023년 5월 29일
0

자바스크립트

목록 보기
23/24

Primitive value

: Strings, Numbers, Booleans, null, undefined, Symbol

  • memory에 저장된다 (주로 stack)
  • when assign to different variable, copies the value
let name = "Max";
console.log(name); //Max
//name의 value를 copy하여 anotherUser에 할당하게 된다.
let anotherUser = name;
console.log(anotherUser); //Max
name="Manuel";
//앞서 anotherUser에는 name의 value를 copy한 값이 할당된 것일 뿐이므로, name이 바뀌었다고 해서 anotherUser의 value까지 바뀌지는 않는다.
console.log(anotherUser);//Max

Reference value

: all other objects

  • stored in memory(Heap), variable stores a pointer(address) to location in memory
  • when assign to different variable, copies the pointer/reference
let hobbies = ['Sports'];
//hobbies이라는 pointer 자체를 copy한다
let newHobbies = hobbies;
console.log(hobbies); //['Sports']
hobbies.push('Cooking');
console.log(hobbies); //['Sports', 'Cooking']
//앞서 pointer 자체를 카피한 것이므로, hobbies를 point하고 있던 newHobbies도 자연히 바뀐다.
console.log(newHobbies);//['Sports', 'Cooking']

그렇다면 array의 value를 카피하고 싶다면 어떻게 해야 할까?
spread 연산자를 사용하면 된다.

let hobbies = ['Sports'];
let moreHobbies = [...hobbies];

Reference value는 다른 변수에 할당될 때 pointer을 복사한다는 점을 이해하면, 왜 두 개의 object가 value가 같아도 그 둘을 ===로 비교했을 때 false가 나오는지 알 수 있다.

const person1 = {age:30};
const person2 = {age:30};
person1 === person2 //false

person1과 person2의 value를 비교하고 있는 것이 아니라 pointer 그 자체를 비교하고 있기 때문에 그 둘은 다를 수 밖에 없는 것이다.

0개의 댓글