[Javascript] 데이터 타입 (Data types) - Primitive / Object
데이터타입은 크게 기본형타입(Primitive type)과 객체타입(Object type)으로 나눌 수 있다.
Primitive type
- Number, String, Boolean, null, undefined, Symbol
1. 기본형타입은 원시타입이라고도 하며, 변수에 값 할당 시 그 값 자체가 메모리에 저장된다.
2. 다른 변수에 다시 그 변수를 할당하면 값이 복사되어서 전달된다.
3. 변경이 불가능하며, 수정을 하면 새로운 참조값(reference)에 값이 할당된다.
Object type
- Object, Function, Array등
1. 데이터와 그 데이터에 관련된 동작(절차, 방법, 기능)을 모두 포함한다.
즉, 속성(Property)과 기능(Method)를 포함할 수 있는 독립적 주체이다.
2. 값을 할당할 때 변수에는 참조값(reference)인 메모리주소가 저장된다.
=> 변수를 선언하고 값을 할당하면 값이 여러개라도 한 reference를 가진다.
reference 변경이 안되는 것이지 할당 값은 수정이 가능하다.
3. 다른 변수에 할당 시 참조값이 할당되어 같은 객체주소를 공유하게 된다.
ex) const person = { name: 'kim', like: 'dogs', dislike: 'bugs', introduce: function() { console.log(`Hello, My name is ${person.name}, I like the ${person.like}. and I dislike the ${person.dislike}. ` ) }, } person.introduce(); // => 출력결과 : Hello, My name is kim, I like the dogs. and I dislike the bugs. const anotherPerson = person; // 새로운 변수에 person 변수 할당 console.log(anotherPerson.name); // => 출력결과 : kim anotherPerson.introduce(); // => 출력결과 : Hello, My name is kim, I like the dogs. and I dislike the bugs. anotherPerson.like = 'food'; // like 속성값 변경 console.log(anotherPerson.like); // => 출력결과 : food console.log(person.like); // => 출력결과 : food |
person이라는 객체변수에서
1. Property는 name, like, dislike이고, Method는 intoroduce function이다.
2. Property들이 값 자체로 저장되는 것이 아니라 참조값(주소)에 저장되는 것이고, Property값 수정이 가능하다.
같은 참조값을 가지고 있기 때문에 anotherPerson.like의 값을 food로 변경했지만 person.name을 수정한 것과 같다.
3. anotherPerson 변수에 person을 할당하니 person의 참조값을 공유하여 같은 내용을 가진다.
* 요약
Primitive type과 Object type의 차이점 :
Primitive type | Object type | |
저장되는 것 | 실제 값(value) 자체 | 값이 저장되어 있는 참조값(reference) |
다른 변수에 할당 시 | 값을 복사하여 저장 | 같은 참조값 공유 |
값 변경 | 불가능 | 가능 |