본문 바로가기

Programming/JavaScript

Primitives vs. Objects in Practice

let firstName = 'Sunjeong';
let oldFirstName = firstName;
firstName = 'Sunny';
console.log(firstName, oldFirstName); // Sunny Sunjeong

const sunny = {
  firstName: 'Sunny',
  lastName: 'Ryu',
  age: 35,
};
const marriedSunny = sunny;
marriedSunny.lastName = 'Y';
console.log('Before marriage: ', sunny);
// Before marriage:  {firstName: 'Sunny', lastName: 'Y', age: 35}
console.log('After marriage: ', marriedSunny);
// After marriage:  {firstName: 'Sunny', lastName: 'Y', age: 35}

원칙적으로 const로 선언된 값은 immutable = not being able to change 변경할 수 없음

그렇지만 여기서는 const가 홀딩하고 있는 값이 실제 value가 아닌 heap에 있는 주소를 가리키기 때문에 변경할 수 있는거다!

marriedSunny = {}; // Uncaught TypeError: Assignment to constant variable.

 

Copying objects

원래 object 값은 유지하면서도 새로운 object의 last name만 변경함

// Copying objects
const sunny2 = {
  firstName: 'Sunny',
  lastName: 'Ryu',
  age: 35,
};

const sunnyCopy = Object.assign({}, sunny2);
sunnyCopy.lastName = 'Y';
console.log('Before marriage: ', sunny2);
// Before marriage:  {firstName: 'Sunny', lastName: 'Ryu', age: 35}
console.log('After marriage: ', sunnyCopy);
// After marriage:  {firstName: 'Sunny', lastName: 'Y', age: 35}

 

가족을 추가해보자.

같은 object를 가리키기 때문에 sunny2와 sunnyCopy에 모두 family 배열이 추가된 걸 알 수 있음

// Copying objects
const sunny2 = {
  firstName: 'Sunny',
  lastName: 'Ryu',
  age: 35,
  family: ['Alice', 'Bob'],
};

const sunnyCopy = Object.assign({}, sunny2);
sunnyCopy.lastName = 'Y';

sunnyCopy.family.push('Mary');
sunnyCopy.family.push('John');

console.log('Before marriage: ', sunny2);
console.log('After marriage: ', sunnyCopy);