JavaScript/TIL

[TIL] #4. TYPE OF

Hello, Big stranger 2020. 8. 17. 15:00

 

Typeof

 

what is typeof?

자바스크립트는 항상 type을 체크해야 한다. ( boolean, string, number 등)

console.log(typeof "11121221") // string
console.log(typeof true) // boolean
console.log(typeof function(){}) // function
console.log(거의 모든 Primitive에서 다 작동을 한다) // Number,boolean,string,undefined..

하지만 여기에 WTF 버그가 있다.

console.log(typeof null) // object

이 버그는 브랜든 그리고 더글라스( 자바스크립트를 만든 개발자)에 의하여 논의가 있었다. Null -> Object 대신 null로 고쳐야 한다는 논의가 있었지만 거절되었다. 그 이유는 이걸 고치면 다른 여러 프로그램들이 영향을 받을까 봐 거절이 되었다. 그래서 WTF 버그이다.

이 같이 비슷한 WTF버그가 있는데 다음과 같다.

console.log(typeof []) // object
console.log(typeof {}) // object

이게 안좋은게 Array인지 object인지 체크하고 싶은데 안되기 때문이다. 그래서 typeof 대신에 instance of를 사용하면 된다.

instance of는 비슷하지만, 유일한 차이점은 이건 primitive(string, boolean, number 등)에서작동하지 않는다는 것이다. 그래서 object, array에선 작동을 한다. 예를 들면 다음과 같다.

console.log([] instanceof Array) // true
console.log({} instanceof Array) // false

 

그래서 기억해놔야 할 것은 Typeof null은 object라는 사실이며, type을 확인하고 싶을 때는 typeof와 instanceof를 잘 사용할 줄 알아야 한다.

'JavaScript > TIL' 카테고리의 다른 글

[TIL] #6. Expression vs. Statement  (0) 2020.08.17
[TIL] #5. Scope  (0) 2020.08.17
[TIL] #3. Type Coercion  (0) 2020.08.16
[TIL] #2. Value Types and Reference Types  (0) 2020.08.16
[TIL] #1. Primitive Types  (0) 2020.08.16