본문 바로가기

Javascript

JavaScript 자바스크립트 typeof() 란 ? 사용법

반응형

 JavaScript 

 

typeof 란 피연산자의 평가 전 자료형을 나타내는 문자열을 반환 

typeof 연산자는 피연산자 앞에 위치한다. 

 

 

기본구문

typeof operand =피연산자   //괄호 없어도 가능 
typeof (operand =피연산자)

 

 

매개변수 

자료형을 가져올 객체 or 원시값을 나타내는 표현식 

 

 

 

반환값 

typeof 는 항상 string으로 반환한다. 

 

 

 

typeof가 반환하는 형식 (result) 

Type Result
Undefined "undefined"
Null "object:
Boolean "boolean"
Number "number"
BigInt "bigint"
String "string"
Symbol "symbol"
호스트객체 (js 환경에서 제공)  구현체마다 다름 
function 객체 "function"
다른 모든 객체  "object"

 

 

 

예제1. 

 

// N U M B E R //
console.log(typeof 10);          // ==='number'
console.log(typeof -10);       // ==='number'
console.log(typeof Math.LN2);    // ==='number' Math.LN2 = 2의 자연로그, 약 0.693
console.log(typeof Infinity);   // ==='number'
console.log(typeof NaN);   // ==='number'
console.log(typeof Number(1));   // ==='number' -> but never use this form!

// B I G I N T //
console.log(typeof 1n);          // ==='bigint'

// S T R I N G //
console.log(typeof '');    // === 'string'
console.log(typeof 'bla');  // === 'string'
console.log(typeof (typeof 1));  // === 'string'
console.log(typeof String(123));  // === 'string'
console.log(typeof String('ab'));  // === 'string'  // never use this form!


// B O O L E A N //
console.log(typeof true);    // ==='boolean'
console.log(typeof false); // ==='boolean'
console.log(typeof Boolean(true)); // ==='boolean' but never use this form!
console.log(typeof Boolean(0)); // ==='boolean'
console.log(typeof 0); // ==='number'   // not false ! 


// S Y M B O L //
console.log(typeof Symbol());     // ==='symbol'
console.log(typeof Symbol('foo'));// ==='symbol'
console.log(typeof Symbol.iterator);// ==='symbol'

// U N D E F I N E D //
console.log(typeof undefined);     // ==='undefined'
console.log(typeof declaredButUndefinedVariable);   // ==='undefined'
console.log(typeof undeclaredVariable);   // ==='undefined'

// O B J E C T S // 
console.log(typeof {a:1});         // === 'object'

// use Array.isArray or Object.prototype.toString.call 
// to differentiate regular objects from arryas 
console.log(typeof [1,2,3]);       // === 'object
console.log(typeof new Date()); // === 'object

// C O N F U S I N G O N E S //
console.log(typeof Boolean(true));  // === 'object' 이라고 적혀있지만 console에는 'boolean'이라고 나옴 
console.log(typeof Number(1));      // === 'object' 이라고 적혀있지만 console에는 'number'
console.log(typeof String('asd'));  // === 'object' 이것도 console에는 'string'

// F U N C T I O N // 
console.log(typeof function(){});   // === 'functinon'
console.log(typeof class C{});      // === 'functinon'
console.log(typeof Math.sin);       // === 'functinon'

 

예제 2 . 

console.log(typeof 'a' === 'string') // true
console.log(typeof 'a' === 'number') // false

 

 

 

반응형