티스토리 뷰

이 글은, JavaScript의 자료형(data types)과 typeof 연산자에 대해 정리한 글입니다.

자료형

먼저 JavaScript의 자료형을 정리해보면 다음과 같습니다.

 

JavaScript Data types

  • boolean
  • number
  • string
  • undefined
  • null
  • symbol (ES6부터 추가)
  • bigint (현재 TC39 stage 3)
  • object

이 중 object를 제외한 나머지를 원시 타입(primitive types)라고 합니다. 또한 여러 Object의 하위 타입(subtype) 이 존재합니다.

 

Sub-Types

  • Function
  • Array
  • Date
  • Error
  • ...

typeof 연산자

typeof를 활용하여 어떤 값이 어떤 자료형인지 알 수 있습니다. 하지만 기대와는 달리 완전히 자료형과 일치한 결과가 나오지는 않습니다.

// 자료형과 일치
typeof true; // "boolean"
typeof 13;   // "number"
typeof "str" // "string"
typeof undefined; // "undefined"
typeof Symbol();  // "symbol" 
typeof 12n;  // "bigint"
typeof {}    // "object"

// 자료형과 불일치
typeof null; // "object"

 

또한 object의 하위 타입인 함수(function)의 경우에는 특별하게 "function"을 반환합니다.

typeof function() {}; // "function"

반면 역시 object의 하위 타입인 배열(array), Date.. 의 경우에는 "object"를 반환합니다.

typeof [1, 2, 3]; // "object"
typeof new Date(); // "object"
typeof Error(); // "object"

Date, Array와 같이 하위 타입까지 구분해야 하는 경우가 있을 수 있습니다. Object.ptototype.toString은 "[object type]" 형태를 반환하는데 이를 이용하여 하위 타입도 구분할 수 있습니다.

Object.prototype.toString.call(1);  // "[object Number]"
Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call({}); // "[object Object]"
Object.prototype.toString.call(()=>{}); // "[object Function]"
Object.prototype.toString.call([1, 2]); // "[object Array]"
Object.prototype.toString.call(new Date()); // "[object Date]"

다음과 같이 정규식으로 필요한 문자열만 뽑아오는 함수를 정의하면 더 쉽게 사용할 수 있습니다. 

const typeOf = (data) => (
  Object.prototype.toString.call(data).match(/([\w]+)\]/)[1]
);


typeOf(1); // "Number"
typeOf("test"); // "String"
typeOf(null); // "Null"
typeOf({}); // "Object"
typeOf([1, 2, 3]); // "Array"
typeOf(new Date());// "Date"

 

참고

 

getify/You-Dont-Know-JS

A book series on JavaScript. @YDKJS on twitter. Contribute to getify/You-Dont-Know-JS development by creating an account on GitHub.

github.com

 

 

자바스크립트의 자료형

모든 프로그래밍 언어는 내장 자료형이 있지만, 종종 이러한 내장 자료형은 언어마다 다르다. 이 문서에서는 자바스크립트의 내장 자료형과, 내장 자료형에서 사용할 수 있는 속성들에 대해 알아본다. 이로써 내장 자료형들로 더 복잡한 자료형을 만드는데 사용할 수 있을 것이다. 가능하다면 다른 언어와도 비교해보자.

developer.mozilla.org

 

'JavaScript Basics' 카테고리의 다른 글

JavaScript Truthy, Falsy  (0) 2019.10.20
JavaScript this  (0) 2019.10.13
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함