데이터 타입을 문자열로 반환
8가지 중 하나로 반환함
"number"
"string"
"boolean"
"bigint"
"undefined"
"symbol"
"object"
"function"
// ex)
typeof '' // "string"
typeof NaN // "number"
typeof null // "object"
typeof 10n // "bigint"
typeof undefined // "undefined"
typeof [] // "object"
typeof {} // "object"
typeof new Date() // "object"
typeof /test/gi // "object"
typeof function () {} // "function"
문제
: typeof null
을 하면 null
이 아닌 “object”
를 반환
이유
: JavaScript 초기버전 설계 오류 때문
그래서 null
을 확인하기 위한 방법
let a = null;
console.log(a === null) // true
console.log(typeof a === null) // false
문제
: 선언하지 않은 식별자에게 "undefined"
를 반환
// ex) apple 이라는 변수는 선언하지 않았음
console.log(typeof apple) // undefined
이유
1. 선언되지 않은 변수에 접근할 때 오류 방지
2. 호환성 및 이전 코드 지원하기 위함
문제
: typeof 배열
을 하면 “object”
를 반환
const arr = [1, 2, 3, 4];
console.log(typeof arr); // object