typeof 연산자는 피연산자의 데이터 타입을 문자열로 반환합니다.
이 글은 코딩에브리바디(codingeverybody.kr)의 내용을 참조해 작성했습니다.
이 연산자는 변수나 값의 데이터 타입을 체크하는데 사용됩니다.
기본 예제
let a;
console.log(typeof a); // 출력: "undefined"
console.log(typeof true); // 출력: "boolean"
console.log(typeof 42); // 출력: "number"
console.log(typeof "Hello"); // 출력: "string"
이 예제는 typeof 연산자가 주어진 값의 데이터 타입을 나타내는 문자열을 반환하는 방식을 보여줍니다. 반환되는 값은 항상 "undefined", "boolean", "number", "string" 등 자바스크립트에서 미리 정의된 타입 이름의 문자열입니다.
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"
데이터 타입과 결과 예
/* Numbers */
typeof 24 === "number"
typeof 3.14 === "number"
typeof NaN === "number"
typeof parseInt("10px") === "number"
typeof Number("2") === "number"
typeof Number("글자") === "number"
/* Strings */
typeof "코딩" === "string"
typeof "" === "string"
typeof `template literal` === "string"
typeof "24" === "string"
typeof String(24) === "string"
/* Booleans */
typeof true === "boolean"
typeof false === "boolean"
typeof Boolean(24) === "boolean"
typeof !!24 === "boolean" // 부정(not)을 의미하는 !을 두 번 호출하면 Boolean()과 동일합니다.
/* Undefined */
var x;
typeof x === "undefined";
typeof undefined === "undefined";
typeof y === "undefined"; // 선언하지 않은 변수도 "undefined"를 반환
/* Objects */
typeof {param: 1} === "object";
typeof {} === "object";
typeof [1, 2, 3] === "object"; // 배열도 "object"를 반환
typeof [] === "object"; // 빈 배열도 "object"를 반환
typeof /regex/ === "object"; // 정규 표현식도 "object"를 반환
typeof null === "object" // null도 "object"를 반환
/* Functions */
function $() {}
typeof $ === "function";
typeof function () {} === "function";
typeof class ClassName {} === "function";
/* Symbols */
typeof Symbol() === "symbol";
typeof Symbol("foo") === "symbol";
/* BigInts */
typeof 1n === "bigint";
typeof BigInt("1") === "bigint";
주의할 점
typeof 연산자는 null을 "object"로 반환합니다. 이는 실제 데이터 타입인 Null과는 다른 점을 주의해야 합니다.
console.log(typeof null); // 출력: "object"
typeof 연산자는 정규 표현식을 "object"로 반환합니다. 이는 정규 표현식이 내부적으로 객체로 처리되기 때문입니다.
let regex = /[a-zA-Z]/;
console.log(typeof regex); // 출력: "object"
배열은 데이터 타입이 객체입니다. 즉 typeof 연산자롤 배열의 타입을 확인하면 "object"를 반환하므로 typeof 연산자만으로는 배열인지 아닌지 확실히 알 수 없습니다.
const arr = [1, 2, 3];
console.log(typeof arr); // 출력: "object"
활용 예제
실제 개발 환경에서는 jQuery와 같은 외부 자바스크립트 라이브러리가 정상적으로 로드되었는지를 확인해야 하는 경우가 종종 있습니다.
정의되지 않은 글로벌 변수를 직접 접근하면 일반적으로 ReferenceError가 발생하지만, typeof 연산자를 사용하면 오류 없이 안전하게 검사할 수 있습니다.
if (typeof jQuery === "function") {
console.log("jQuery가 로드되어 사용 가능합니다.");
} else {
console.log("jQuery가 로드되지 않았습니다.");
}
참고 자료
https://codingeverybody.jp/javascript-typeof-operator/
JavaScript typeof 演算子:データ型を確認する - codingEverybody
JavaScriptにおいて、typeof演算子はオペランドのデータ型を文字列で返します。この演算子は、変数や値のデータ型を確認するために使用されます。
codingeverybody.jp
https://coding.courses/javascript-typeof-operator/
JavaScript typeof Operator – Checking Data Types - codingCourses
The typeof operator returns a string indicating the data type of a given operand. It is commonly used to check the type of a variable or value.
coding.courses