Home 01.Type
Post
Cancel

01.Type

타입

내장 타입

자바스크립트에는 다음 7가지 내장 타입이 존재한다.

  • null
  • undefined
  • number
  • string
  • boolean
  • object
  • symbol

이 중 object를 제외한 나머지 타입들은 원시 타입이라고 부른다.

typeof

이러한 타입들은 typeof연산자를 사용해서 알 수 있는데 놀랍게도 typeof의 반환값이 항상 위에서 언급한 7가지 타입에 1:1로 대응되지 않는다.

1
2
3
4
5
6
7
8
console.log(typeof undefined); // undefined
console.log(typeof true); // boolean
console.log(typeof 1); // number
console.log(typeof '2'); // string
console.log(typeof {}); // object
console.log(typeof Symbol()); // symbol

console.log(typeof null); // object...?

다른 친구들은 다 자신의 타입 명칭과 동일한 문자열을 내뱉는데 null은 혼자서 object를 반환하고 있다.

이는 버그이지만.. 너무 오랫동안 방치되어온 버그라 해결될 가능성이 거의 없다고 한다.

그래서 null값을 정확히 확인하려면 다음과 같이 비교하여야한다.

1
2
const a = null;
console.log(!a && typeof a === 'object'); // true

비교하려는 값이 falsy한 값인데 typeofobject를 반환하고 있다면 그 값은 null임을 확인하는 조건

1대1 대응되지 않는 이유는 한가지가 더 존재하는데

1
2
const a = () => {};
console.log(typeof a); // function

typeof로 함수를 판별할 경우 7가지 타입에 존재하지 않는 function이라는 문자열을 반환한다.

그렇다면 function은 7가지 타입에 더불어 존재하는 최상위 내장 타입 중 하나여야하는게 아닐까..하는 의문이 들지만 실제로는 object의 하위 타입이다.

이처럼 함수는 호출 가능한 객체이며 내부프로퍼티로 call 메서드를 호출할 수 있는 객체를 함수라고 정의하고 있다.

undefined vs undeclared

undefined은 값이 없음을 나타낸다. 그렇다면 초기화 되지 않은 변수도 값이 없는 것이니 undefined일까?

1
2
3
let a;
console.log(a); // undefined
console.log(b); // Error: b is not defined

자바스크립트는 선언되었지만 값이 할당되지 않은 변수에 undefined를 내뱉고 있지만 아예 선언조차 되지 않은 무언가에 대해서는 is not defined라는 에러를 뱉는다.

is not defined라니.. 결국 undefined이라는 소리 아닌가 싶은데.. 명확하지 않다고 생각할 수 있지만 에러를 뱉는 점에서 다르니까 넘어가자

문제는 선언되지 않은 변수에 typeof를 사용했을 때다.

1
2
console.log(typeof a); // undefined
console.log(typeof b); // undefined

놀랍게도 둘 다 undefined라는 결과가 나오는데 자바스크립트는 값이 없는 변수와 선언되지 않은 변수 모드 undefined로 처리한다.

This post is licensed under CC BY 4.0 by the author.