Javascript의 타입은 크게 원시 타입(Primitive type)과 참조 타입(Reference type)으로 분류할 수 있는데 최초에 타입을 구분하더라도 runtime 환경에서 동적으로 타입이 변경될 수 있는 언어이기 때문에 타입을 구분하여 다루는 것이 매우 까다롭다.
원시타입으로 분류되는 유형(string, boolean, number, undefined, symbol)은 typeof를 이용한 타입 검사 결과를 잘 활용할 수 있지만 reference 유형은 함수, 클래스, 객체, 배열 등을 구분하지 못하고 object 타입으로 분류되기 때문에 상세하게 감별하기가 어렵다.
// 'typeof null'은 언어적인 오류로 인해 'object'로 분류된다.
// 이 오류가 reference type의 분류를 더 어렵게 만든다.
type of null // 'object'
function Person(name, age) {
this.name = name;
this.age = age;
}
const poco = new Person('poco', 99);
poco instanceof Person // true
reference type은 prototype chain을 거슬러 올라가 보면 최상위는 결국 객체이므로 instanceof 타입 검사시 주의가 필요하다.
const arr = [];
const func = function() {};
const date = new Date();
arr instanceof Array // true
func instanceof Function // true
date instanceof Date // true
arr instanceoff Object // true
func instanceof Object // true
date instanceof Date // true
const arr = [];
Object.prototype.toString.call(arr) //'[object Array]'
// 1. null: 암시적으로 값이 없는 것을 의미함
!null //true
!!null //false
// null을 수학 연산에서 사용하면 0에 가까운 값이다.
null + 123 //123
// 2.undefined: 어떤 값도 할당되지 않은 상태(값이 있는지 없는지도 모르는 상태)
let a;
a //undefined
// undefined를 수학 연산에서 사용하면 유효하지 않은 값으로 취급된다.
undefined + 10 //NaN
// equal operator(==)를 사용할 경우, 헤깔리는 결과가 나올 수 있으므로
// 항상 strict equal operator(===)를 사용하자.
!undefined //true
undefined == null //true
undefined === null //false
!undefined === !null //true
출처: 클린코드 자바스크립트-장현석