typeof
연산자
typeof
연산자는
피연산자의 데이터 타입을 문자열로 반환하는 연산자입니다.
let a;
console.log(typeof a); // 출력: "undefined"
console.log(typeof true); // 출력: "boolean"
console.log(typeof 42); // 출력: "number"
console.log(typeof "Hello"); // 출력: "string"
typeof
연산자의 구문
typeof operand // operand는 피연산자를 의미함
operand
데이터 타입을 판별하려는 변수나 값입니다.
좀 더 정확히 말하자면, 반환되는 데이터 타입을 확인하려는 객체나 기본(primitive) 데이터 값을 나타내는 표현식입니다.
이 표현식은 typeof
연산자의 오른쪽에 위치하며, typeof
연산자는 이 표현식을 평가하여 해당 값의 데이터 타입을 판별하고 그 결과를 문자열로 반환합니다. operand
는 변수, 상수, 리터럴 값, 함수 호출 등이 될 수 있습니다.
간단한 예제를 통해 설명하겠습니다.
let x = 42;
let y = "Hello";
let z = {key: "value"};
console.log(typeof x); // 출력: "number"
console.log(typeof y); // 출력: "string"
console.log(typeof z); // 출력: "object"
위 예제에서 x
, y
, z
는 모두 다른 데이터 타입을 가진 변수입니다.
typeof
연산자는 각각의 변수를 operand
로 받아 해당 변수의 데이터 타입을 문자열로 반환합니다.
정리하면, operand
는 typeof
연산자의 작동 대상이 되는 값 또는 표현식을 가리키며, 이 값의 데이터 타입을 확인하고 싶을 때 사용됩니다.
typeof
연산자로 확인할 수 있는 주요 데이터 타입과 결과
데이터 타입 | 결과 |
---|---|
undefined | "undefined" |
boolean | "boolean" |
number | "number" |
string | "string" |
object | "object" |
function | "function" |
symbol | "symbol" |
bigint | "bigint" |
let a;
console.log(typeof a); // 출력: "undefined"
console.log(typeof true); // 출력: "boolean"
console.log(typeof 42); // 출력: "number"
console.log(typeof "Hello"); // 출력: "string"
console.log(typeof {}); // 출력: "object"
console.log(typeof [1, 2, 4]); // 출력: "object"
console.log(typeof new Date()); // 출력: "object"
console.log(typeof null); // 출력: "object"
console.log(typeof function() {}); // 출력: "function"
console.log(typeof class C {}); // 출력: "function"
console.log(typeof Math.sin); // 출력: "function"
console.log(typeof Symbol("foo")); // 출력: "symbol"
console.log(typeof 123n); // 출력: "bigint"
typeof
연산자로 확인 시 주의해야 할 점
null
타입
typeof
연산자는 null
을 "object"
로 반환합니다. 이는 실제 데이터 타입인 null과는 다른 점을 주의해야 합니다.
console.log(typeof null); // 출력: "object"
정규식 표현
typeof
연산자는 정규표현식을 "object"
로 반환합니다. 이는 정규표현식이 내부적으로 객체로 처리되기 때문입니다.
let regex = /[a-zA-Z]/;
console.log(typeof regex); // 출력: "object"
배열 확인
자바스크립트에서 변수나 값이 배열인지 확인해야 하는 경우가 많습니다.
배열은 데이터 타입이 객체입니다. 즉 typeof
연산자롤 배열의 타입을 확인하면 "object"
를 반환하므로 typeof
연산자만으로는 배열인지 아닌지 확실히 알 수 없습니다.
자바스크립트에서 배열을 확인할 때는 Array.isArray()
메서드를 사용하는 것이 가장 정확합니다. Array.isArray()
메서는
전달된 인수가 배열이면 true
, 배열이 아니면 false
를 반환합니다.
const arr = [1, 2, 3];
console.log(Array.isArray(arr)); // true
typeof
연산자의 명세서
명세서 사양 | |
---|---|
typeof
|
ECMAScript Language Specification #sec-typeof-operator |
typeof
연산자의 브라우저 호환성
연산자 |
Chrome
|
Edge
|
Firefox
|
Safari
|
---|---|---|---|---|
typeof
|
1 | 12 | 1 | 1 |