JavaScript Primitive vs Reference Values

Yunwoo Ji·2021년 6월 15일
0

JavaScript

목록 보기
2/4
post-thumbnail

Ref : https://www.javascripttutorial.net/javascript-primitive-vs-reference-values/

Primitive type

종류

  • undefined
  • null
  • boolean
  • number
  • string
  • symbol

특징

  • 사이즈가 고정되어져 있다.
  • stack에 저장된다.
  • primitive value가 할당된 variable에 접근할 때, 우리는 variable에 저장된 실제 값을 조종하게 된다. 다르게 말하면, variable은 값에 의해 접근된다.
  • typeof operator를 통해 primitive value의 type을 확인할 수 있다.
let n = 10;
console.log(typeof(n));
// expected output: number
  • primitive value가 할당된 variable을 다른 variable에 할당할 때, value는 새로 생성되고, 새로운 variable로 copy된다.
let a = 10;
let b = a; // a에서 b로 숫자 10이 복사된다.
b = 20; // a와 b는 관계가 없기 때문에, b의 값을 바꾸어도 a의 값은 바뀌지 않는다.
console.log(a);
// expected output: 10
console.log(b);
// expected output: 20

Reference type

종류

  • object

특징

  • 사이즈가 동적이다.
  • heap에 저장된다.
  • reference value인 object가 할당된 variable에 접근할 때, 우리는 실제 값이 아닌, object의 reference를 조종하게 된다. 다르게 말하면, variable은 reference에 의해 접근된다.
  • instanceof operator를 통해 reference value의 type을 확인할 수 있다.
let rgb = ['red','green','blue'];
console.log(rgb instanceof Array);
// expected output: true
  • reference value가 할당된 variable을 다른 variable에 할당할 때, value는 새로운 variable로 copy된다. 차이점은 두 variable 모두 heap에 저장된 실제 object의 주소를 가르킨다. 결과적으로, 두 variable 모두 같은 object를 reference하고 있는 것이다.
let a = {name: 'John'};
let b = a;
b.name = 'David'; // b의 name 값을 수정
console.log(a.name);
// expected output: David
// a와 b는 같은 object를 reference하고 있기 때문에, a variable에도 변경된 값이 반영된다.
profile
Front-End !

0개의 댓글