Programing/javascript

자바스크립트의 데이터 타입 완전 정복 (typeof, null, undefined)

Dongkkase 2025. 4. 23. 11:14
반응형

자바스크립트를 다루다 보면 typeof, null, undefined의 개념에서 헷갈리는 경우가 많습니다. 특히 예상과 다른 결과값이나 데이터 타입 판별 문제로 디버깅이 어려울 때가 있죠. 이 글에서는 자바스크립트의 기본 데이터 타입을 정확하게 이해하고, typeof, null, undefined를 명확히 구분하는 방법을 정리해보겠습니다.


✨ 자바스크립트의 기본 데이터 타입

자바스크립트의 데이터 타입은 크게 원시 타입참조 타입으로 나뉩니다.

✅ 원시 타입 (Primitive Types)

  • string: 문자열 → 'hello', "abc"
  • number: 숫자 → 10, 3.14, NaN
  • boolean: 참/거짓 → true, false
  • undefined: 값이 할당되지 않은 변수
  • null: 값이 "없음"을 명시
  • bigint: 큰 정수 (ES2020 도입)
  • symbol: 고유한 식별자 (ES6 도입)

✅ 참조 타입 (Reference Types)

  • object: 배열, 객체, 함수 등

🔍 typeof 연산자란?

typeof는 변수의 타입을 문자열로 반환합니다.

typeof "hello"     // "string"
typeof 123          // "number"
typeof true         // "boolean"
typeof undefined    // "undefined"
typeof null         // ❗ "object" ← 주의!
typeof {}           // "object"
typeof []           // "object"
typeof function(){} // "function"

⚠️ typeof null === "object"가 되는 이유

  • 이는 자바스크립트의 초기 설계 실수로, 오랫동안 호환성을 위해 그대로 유지되고 있습니다.
  • null은 실제로 원시 타입이지만, typeof로는 "object"로 판별되므로 주의가 필요합니다.

🔍 undefined vs null

구분 의미 typeof 결과
undefined 값이 할당되지 않음 "undefined"
null 일부러 "없음"을 명시한 상태 "object" (주의)

예시:

let a;
console.log(a);         // undefined

let b = null;
console.log(typeof b);  // "object"

🧪 typeof 한눈에 보기

typeof 42              // "number"
typeof "hello"         // "string"
typeof true            // "boolean"
typeof undefined       // "undefined"
typeof null            // "object" ❗
typeof {}              // "object"
typeof []              // "object"
typeof Symbol()        // "symbol"
typeof BigInt(123)     // "bigint"
typeof function(){}    // "function"

✅ 정리

  • typeof는 유용하지만 nullarray를 구분하는 데 한계가 있습니다.
  • 배열인지 여부는 Array.isArray()를 사용하는 것이 정확합니다.
  • undefined는 기본적으로 "값이 없다", null은 "명시적으로 없다"는 의미를 구분하여 사용해야 합니다.
반응형