JavaScript Typeof
JavaScript typeof
: 데이터 타입 확인하기
JavaScript에서 typeof
연산자는 데이터 타입을 확인하는 데 사용됩니다. 변수가
숫자인지, 문자열인지, 객체인지 등을 확인하는 데 유용하며, 데이터 유형에 따라 다른 작업을 수행해야 할 때 주로
사용됩니다.
이 가이드는 typeof
연산자의 사용법과 그 결과로 반환되는 데이터 타입에 대해 설명합니다.
1. typeof
의 기본 개념
typeof
연산자는 피연산자의 데이터 유형을 문자열로 반환합니다. 이 연산자는 JavaScript에서 일반적인
데이터 유형을 구분하는 데 유용합니다.
1.1. 기본 구문
typeof 피연산자;
- 피연산자:
typeof
연산자가 검사할 값 또는 변수입니다. - 반환값: 데이터 유형을 나타내는 문자열이 반환됩니다.
2. typeof
반환값
typeof
연산자는 다양한 데이터 타입에 대해 특정 문자열을 반환합니다. 아래는 각 데이터 타입에 따른 반환값입니다.
데이터 타입 | 반환값 |
---|---|
숫자 | "number" |
문자열 | "string" |
불리언 | "boolean" |
객체 | "object" |
배열 | "object" |
함수 | "function" |
undefined |
"undefined" |
null |
"object" |
심볼 | "symbol" |
BigInt | "bigint" |
3. typeof
의 사용 예시
3.1. 숫자 타입 확인
let age = 25;
console.log(typeof age); // 출력: "number"
3.2. 문자열 타입 확인
let name = "Alice";
console.log(typeof name); // 출력: "string"
3.3. 불리언 타입 확인
let isAdult = true;
console.log(typeof isAdult); // 출력: "boolean"
3.4. 객체 타입 확인
let person = { name: "Alice", age: 25 };
console.log(typeof person); // 출력: "object"
3.5. 배열 타입 확인
배열도 객체로 취급되므로 typeof
연산자는 배열을 "object"
로 반환합니다.
let fruits = ["apple", "banana", "cherry"];
console.log(typeof fruits); // 출력: "object"
3.6. 함수 타입 확인
function greet() {
return "Hello!";
}
console.log(typeof greet); // 출력: "function"
3.7. undefined
타입 확인
변수가 선언되었지만 값이 할당되지 않은 경우 typeof
는 "undefined"
를 반환합니다.
let notDefined;
console.log(typeof notDefined); // 출력: "undefined"
3.8. null
타입 확인
- *
null
*은 객체가 아니지만, 역사적인 이유로typeof null
은"object"
를 반환합니다. 이는 JavaScript에서 오래전부터 존재하던 설계상의 문제로, 수정되지 않은 상태로 유지되고 있습니다.
let emptyValue = null;
console.log(typeof emptyValue); // 출력: "object"
3.9. symbol
타입 확인
심볼(symbol)은 고유한 식별자를 생성하는 데 사용되는 데이터 유형입니다.
let symbol = Symbol("id");
console.log(typeof symbol); // 출력: "symbol"
3.10. BigInt
타입 확인
BigInt는 매우 큰 정수를 표현할 수 있는 데이터 유형입니다.
let bigIntValue = 123456789012345678901234567890n;
console.log(typeof bigIntValue); // 출력: "bigint"
4. typeof
와 비교하기
typeof
는 타입 검사와 조건문에서 자주 사용됩니다. 특정 데이터 타입에 따라 조건을 다르게 처리할 수 있습니다.
4.1. 타입에 따라 다른 작업 수행
let value = 42;
if (typeof value === "number") {
console.log("숫자입니다.");
} else if (typeof value === "string") {
console.log("문자열입니다.");
} else {
console.log("알 수 없는 타입입니다.");
}
// 출력: 숫자입니다.
5. typeof
사용 시 주의사항
5.1. null
반환값이 "object"
인 이유
- *
null
*은 객체가 아니지만,typeof null
은 **"object"**를 반환합니다. 이는 JavaScript 초기 버전에서의 설계상의 문제로, 그 이후에도 수정되지 않고 유지되었습니다.null
을 확인할 때는typeof
대신 엄격한 비교(===
)를 사용하는 것이 좋습니다.
let value = null;
if (value === null) {
console.log("값이 null입니다.");
}
// 출력: 값이 null입니다.
5.2. 배열과 객체 구분하기
typeof
로는 배열과 객체를 구분할 수 없습니다. 배열을 구분하려면 Array.isArray()
메서드를 사용하는 것이 좋습니다.
let arr = [1, 2, 3];
let obj = { name: "Alice" };
console.log(typeof arr); // 출력: "object"
console.log(Array.isArray(arr)); // 출력: true
console.log(Array.isArray(obj)); // 출력: false
6. instanceof
와 typeof
의 차이
- *
typeof
*는 변수의 기본 데이터 타입을 확인하는 데 사용되고, **instanceof
*는 객체의 생성자 함수를 기반으로 특정 클래스의 인스턴스인지 확인하는 데 사용됩니다.
6.1. instanceof
사용 예시
let arr = [1, 2, 3];
console.log(arr instanceof Array); // 출력: true
console.log(arr instanceof Object); // 출력: true
- *
typeof
*는 배열을"object"
로 반환하지만, **instanceof
*는 배열이 실제로 **Array
*의 인스턴스인지 확인합니다.
요약
typeof
연산자는 변수의 데이터 타입을 확인하고 문자열로 반환합니다.- 반환값:
"number"
,"string"
,"boolean"
,"object"
,"undefined"
,"function"
,"symbol"
,"bigint"
- 객체와 배열:
typeof
는 객체와 배열을 모두"object"
로 반환합니다. 배열을 구분하려면 **Array.isArray()
*를 사용해야 합니다. - *
null
*은"object"
를 반환하지만, 실제로는 객체가 아니므로 주의가 필요합니다.
typeof
는 JavaScript에서 데이터 타입을 확인하는 가장 기본적인 방법으로, 조건문이나 디버깅 시 유용하게 사용할 수 있습니다.