Sangil's blog

https://github.com/ChoiSangIl Admin

javascript에도 reference type이!? DEV / JAVASCRIPT

2020-12-14 posted by sang12


업무를 하며 항상 javascript를 사용 했는데, 참 많이 모르고 사용하고 있구나란 생각이 든다.

javascript에서도 java와 같이 primitive type과 reference type이 나눠져 있다. 

primitive type은 아래와 같이 총 6가지가 있다. (Null과 Undefiend도 하나의 type이였구나) primitive type은 말그대로 원시적인 값 그 자체를 같는다. 

  • String
  • Boolean
  • Null
  • Undefined
  • Number
  • Symbol
-primitive type example
//primitive type
let a = "10";
let b = "20";
console.log(typeof a, typeof b); //string string
console.log(a, b); //10 20
b = a;
a = "100";
console.log(a, b); //100 10

JavaScript에서의 type은 데이터에 따라 컴파일될 당시에 정해지며 typeof를 이용하여 typ을 조회 할 수 있다. 


reference type으로는 Array, Object, Date type등이 있습니다. 

  • Arrays
  • Object
  • Date
-reference type example
//reference type
let c = {
    a:10,
    b:20
}
let d = {
    a:30,
    b:40
}

console.log(typeof c, typeof d); //object object
console.log(c.a, c.b);  //10 20
console.log(d.a, d.b);  //30 40
c=d;
c.a=100;
console.log(c.a, c.b);  //100 40
console.log(d.a, d.b);  //100 40

reference type은 primitive타입과 다르게 c=d로 할당하면, c에 d의 레퍼런스값이 할당 되기 때문에 c의 값을 변경하면, d의 값도 같이 변경되는 것을 볼 수 있습니다.

#javascript 자료형 #javascript primitive type
REPLY