타입(자료형)

손수민·2023년 6월 4일
0

JavaScript

목록 보기
2/2
post-thumbnail

타입

데이터를 용도에 맞게 쓰기 위해서 사용
컴퓨터에게 해당 데이터가 앞으로 어떻게 처리될지를 정함
단순한 데이터를 저장하는 원시타입과 객체로서 저장되는 참조타입으로 구별

타입을 체크하는 방법

  1. typeof 연산자
typeof 10; // "number"
typeof "sumin"; // "string"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object"
  1. instanceof 연산자
    객체의 생성자 함수를 비교하여 타입을 체크( 상속 체인까지 확인한다.)
let arr = [1, 2, 3];
let obj = { name: "sumin", age: 27 };

arr instanceof Array; // true
obj instanceof Object; // true
  1. Object.prototype.toString.call 함수
    객체의 타입을 문자열로 반환(call 메소드를 활용)
    가장 정확한 방법중 하나
Object.prototype.toString.call(10); // "[object Number]"
Object.prototype.toString.call("sumin"); // "[object String]"
Object.prototype.toString.call(true); // "[object Boolean]"
Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call(null); // "[object Null]"

원시타입

값이 변경 불가능
원시 값을 다른 변수에 할당 할때는 값의 참조가 저장되는 것이 아닌, 값 자체(가리키고 있는 값을 따라가서 실제 메모리에 저장된 주소)가 복사되어 저장

let a = 'hello';
let b = a;
console.log(b); // 'hello'

a = 'world';
console.log(b); // str2에 할당된 값은 여전히 'hello' 입니다.

string, number, bigint, boolean, undefined, symbol, null 등이 원시타입에 속한다.

객체타입

프로퍼티(상태)와 메서드(동작)를 가진다.
값을 변수에 저장할 때 값 자체가 아닌 값의 위치가 저장.객체 값을 다른 변수에 할당 할때는 값 자체가 복사되어 저장되는 것이 아닌 값의 참조(위치)가 저장
JavaScript는 call by value만 존재

let a = [1, 2, 3];
let b = a;
console.log(b);///[1, 2, 3]

a[0] = 10;
// a = [10, 20];
console.log(b);///[10, 2, 3]

// 비교해보세요.
let c = 10;
let d = value1;
console.log(d);///10

c = 20;
console.log(d);///10

배열 (Array),객체 (Object)가 객체타입에 포함된다.

profile
개발 유망주

0개의 댓글