
JavaScript에서의 typeof 연산자
JavaScript에서 typeof 연산자는 변수의 자료형을 확인하는 데 사용됩니다. typeof는 변수나 값의 유형을 문자열로 반환하여, 코드에서 데이터 타입을 다루거나 디버깅할 때 유용합니다.
typeof 사용법typeof는 연산자이므로 함수 호출이 아닌 피연산자 앞에 사용됩니다.
console.log(typeof 42); // 'number'
console.log(typeof 'Hello'); // 'string'
console.log(typeof true); // 'boolean'
typeof 연산자가 반환하는 자료형에는 다음이 있습니다:
'undefined': 변수가 선언되었지만 값이 할당되지 않은 경우
let x;
console.log(typeof x); // 'undefined'
'boolean': 불린형 값
console.log(typeof true); // 'boolean'
'number': 숫자형 값
console.log(typeof 42); // 'number'
console.log(typeof NaN); // 'number'
'string': 문자열
console.log(typeof 'Hello, World!'); // 'string'
'object': 객체 또는 null
console.log(typeof { name: 'Alice' }); // 'object'
console.log(typeof null); // 'object'
'function': 함수
function greet() {
return 'Hello';
}
console.log(typeof greet); // 'function'
'symbol': 심볼 (ES6부터)
let sym = Symbol('unique');
console.log(typeof sym); // 'symbol'
'bigint': BigInt (ES2020부터)
let bigNumber = 12345678901234567890n;
console.log(typeof bigNumber); // 'bigint'
null 값
null은 비어 있는 객체를 나타내지만, typeof 연산자는 이를 'object'로 반환합니다. 이는 JavaScript의 초기 설계에서 발생한 오류로, 여전히 남아 있습니다.console.log(typeof null); // 'object'
배열
typeof는 배열을 'object'로 반환합니다. 배열 여부를 확인하려면 Array.isArray()를 사용하세요.let arr = [1, 2, 3];
console.log(typeof arr); // 'object'
console.log(Array.isArray(arr)); // true
typeof 연산자는 JavaScript에서 데이터 유형을 확인하는 데 유용한 도구입니다. 각 자료형의 반환값을 이해하고, null과 배열을 확인할 때의 주의 사항을 숙지하여 코드를 작성하세요.