How to check the type of a variable
Short answer
The typeof operator returns the type as a string:
console.log(typeof 42);
console.log(typeof 'hello');
console.log(typeof true);
console.log(typeof undefined);
console.log(typeof (() => {}));Output:
number
string
boolean
undefined
functionSpecial cases
For null and arrays typeof says object. Check them separately:
console.log(typeof null, typeof [1, 2]);
console.log(Array.isArray([1, 2]), [1, 2] === null);Output:
object object
true falseObjects of classes
instanceof checks which class an object was created from:
console.log(new Date() instanceof Date);
console.log(new Error('oops') instanceof Error);
console.log([] instanceof Object);Output:
true
true
trueA universal function
Object.prototype.toString gives a precise name for any value:
const typeOf = (value) => Object.prototype.toString.call(value).slice(8, -1);
console.log(typeOf(null), typeOf([]), typeOf(new Date()), typeOf(/a/), typeOf(new Map()));Output:
Null Array Date RegExp MapCommon mistake
Checking typeof value === 'object' lets null through, and reading a property of it throws an error:
const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
console.log(typeof null === 'object');
console.log(isObject(null), isObject({}), isObject([]));Output:
true
false true falseFunctions used in this recipe
- typeof — Returns a string with the type of a value.
- Array.isArray — Checks whether a value is an array.
- instanceof — Checks whether an object was created by a class (or a subclass).