The typeof operator
suggest changeThe typeof
operator returns the data type of the un-evaluated operand as a string.
Syntax:
typeof operand
Returns:
These are the possible return values from typeof
:
Type | Return value |
---|---|
Undefined | "undefined" |
Null | "object" |
Boolean | "boolean" |
Number | "number" |
String | "string" |
Symbol (ES6) | "symbol" |
Function object | "function" |
document.all | "undefined" |
Host object (provided by the JS environment) | Implementation-dependent |
Any other object | "object" |
The unusual behavior of document.all
with the typeof
operator is from its former usage to detect legacy browsers. For more information, see http://stackoverflow.com/q/40643613/6388243
Examples:
// returns 'number'
typeof 3.14;
typeof Infinity;
typeof NaN; // "Not-a-Number" is a "number"
// returns 'string'
typeof "";
typeof "bla";
typeof (typeof 1); // typeof always returns a string
// returns 'boolean'
typeof true;
typeof false;
// returns 'undefined'
typeof undefined;
typeof declaredButUndefinedVariable;
typeof undeclaredVariable;
typeof void 0;
typeof document.all // see above
// returns 'function'
typeof function(){};
typeof class C {};
typeof Math.sin;
// returns 'object'
typeof { /*<...>*/ };
typeof null;
typeof /regex/; // This is also considered an object
typeof [1, 2, 4]; // use Array.isArray or Object.prototype.toString.call.
typeof new Date();
typeof new RegExp();
typeof new Boolean(true); // Don't use!
typeof new Number(1); // Don't use!
typeof new String("abc"); // Don't use!
// returns 'symbol'
typeof Symbol();
typeof Symbol.iterator;
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents