TIL. 55 typeof

조윤식·2022년 9월 12일
0

typeof 연산자

typeof 연산자는 피연산자의 데이터 타입을 문자열로 반환한다. 총 7가지 문자열 string, number, boolean, undefined, symbol, object, function 중 한 개를 반환한다. null을 반환하는 경우는 없으며, 함수의 경우 function을 반환한다.

typeof(null)의 결괏값은 null이 아니라 object를 반환하는데 주의하자. 이것은 자바스크립트의 첫 번째 버전의 버그다.(typeof null의 역사) 하지만 기존 코드에 영향을 줄 수 있기 때문에 아직까지 수정되지 못하고 있다. 만약, null 타입인지 확인하고 싶다면 일치 연산자(===)를 사용하여 확인하자.

선언하지 않은 식별자를 typeof 연산자로 연산해보면 ReferenceError가 발생하지 않고 undefined를 반환한다.

typeof ('') // string
typeof (1) // number
typeof (NaN) // number
typeof (true) // boolean
typeof (undefined) // undefined
typeof (Symbol()) // symbol
typeof (null) // object
typeof ([]) // object
typeof ({}) // object
typeof (new Date()) // object
typeof (/test/gi) // object
typeof (function(){}) // function
let a = null
a === null // true
typeof(nothing) // undefined

profile
Slow and steady wins the race

0개의 댓글