javascript는 동적인 타입을 가지는 언어이기 때문에 타입 검사가 어렵다.
따라서 primitive(원시)와 reference(참조) 타입을 검사하는 것도 중요하다.
primitive한 타입에는 string, number, bigint, boolean, undefined, symbol, null 이 있다. -> 참고
또한 reference data type에는 Objects, Functions, Collections, Arrays, Dates, 그리고 objects의 다른 type들이 있다. -> 참고
이러한 타입들을 검사하기 위해 javascript에서는 typeof나 instanceof같은 키워드로 검사할 수 있다.
typeof 는 주로 primitive한(불변하는) value들을 검사할 수 있는데,
instanceof 는 객체에 대해 확인할 때 용이하다.
typeof value는 value에 대한 타입을 알 수 있게 해주고,
value1 instanceof Array는 value1이 Array인지 아닌지 true or false로 알 수 있게 해준다.
하지만 예를 들어, 다음과 같은 결과를 통해 혼란이 올 수 있게 된다.
const arr = []
const func = function() {}
const date = new Date()
arr instanceof Obejct -> true
function instanceof Obejct -> true
date instanceof Obejct -> true
왜일까?
그 이유는 Array, Function, Date과 같은 객체는 레퍼런스 타입이고,
결국 최상위는 Object이기 때문에 모두 true가 나오는 것이다.
따라서 instanceof 로는 타입 구별이 어렵기 때문에 typeof와 같은 연산자가 나오게 된 것이다.
위와 같은 상황에선 다음과 같이 Object의 prototype에서 call을 통해 가져와 검사를 할 수 있다.
Object.prototype.toString.call(arr)
-> '[object Array]'
Object.prototype.toString.call(func)
-> '[object Function]'
Object.prototype.toString.call(date)
-> '[object Date]'