언어/JavaScript

[javascript] 데이터 타입의 종류, typeof

dv_jamie 2022. 5. 15. 00:18

데이터 타입 종류

Primitive type Reference type
number array
string function
boolean date
null regExp
undefined map, weakMap
symbol set, weakSet

* ESC6 에서 추가 : symbol, map, weakMap, set, weakSet

 

 

typeof 로 체크해봤는데 이상한 점 발견

  • typeof : 데이터 타입을 문자열로 반환하는 연산자 (연산자이므로 괄호를 안 써줘도 됨)
const func = () => {
    return 1
}
const obj = {a: 1, b: 2}
const arr = [1, 2, 3]

console.log(typeof func) // function
console.log(typeof obj) // object
console.log(typeof arr) // object
console.log(typeof null) // object
console.log(typeof undefined) // undefined

배열, null 모두 object를 반환함..
찾아봤더니 typeof의 반환값은 아래와 같다 (mdn 참고함)

type result
undefined "undefined"
null "object"
boolean "boolean"
number "number"
bigInt "bigint"
string "string"
symbol "symbol"
function "function"
다른 모든 객체 "object"
호스트 객체 구현체마다 다름

* array도 object를 반환함 (array 도 일종의 object라고 함)
-> 따라서 배열 체크를 위해서는 isArray( )를 사용