Get the type of a value with typeof in JavaScript
Intermediate · 4 min read
Sometimes your code receives a value and needs to know what kind of thing it is. Is it a number someone typed, a string from a form, a function to call later? JavaScript's typeof operator answers that question, and writing a function around it is a good way to learn its quirks.
In this tutorial you will write typeOf, a function that returns the type of whatever you pass in. You will find out that typeof has eight possible answers, not the six older references list, and that it has a famous bug with null. Then you will write a sharper version, preciseType, that can tell arrays, dates and null apart. You only need to know what a function is.
What a type is
Every value in JavaScript has a type, the kind of value it is. 42 is a number, 'hello' is a string, true is a boolean (a yes or no value). The type decides what you can do with it: you can multiply numbers and you can upper-case strings.
typeof is written in front of a value and gives back its type as a string:
console.log(typeof 42); // 'number'
console.log(typeof 'hello'); // 'string'
console.log(typeof true); // 'boolean'
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
9 Return the type of an argument
fairReturn the type of whatever is passed in. Older references say typeof has six possible results; check that.
Stuck? Three hints, smallest first
- 1.
typeofnow has eight results, not six. Two were added to the language later. - 2.
typeof nullis‘object’, which is a permanent bug. - 3. For a useful answer,
Object.prototype.toStringdistinguishes arrays, dates and null.
Step 1: wrap typeof in a function
The function itself is one line. It passes the value straight to typeof:
const typeOf = (value) => typeof value;
console.log(typeOf({})); // 'object'
console.log(typeOf(() => {})); // 'function'
console.log(typeOf(undefined)); // 'undefined'
So far that is five results: number, string, boolean, object, function. undefined makes six. That is the list many older references give.
Step 2: the two newer types
Two more types were added to the language later. A BigInt is a whole number of any size, written with an n at the end. A Symbol is a unique label, mostly used as a special object key:
console.log(typeOf(1n)); // 'bigint'
console.log(typeOf(Symbol('s'))); // 'symbol'
That makes eight possible results: 'object', 'boolean', 'function', 'number', 'string', 'undefined', 'bigint' and 'symbol'. Any list of six is out of date.
Step 3: where typeof gives a vague answer
Now try some values that are not plain objects:
console.log(typeOf(null)); // 'object'
console.log(typeOf([])); // 'object'
console.log(typeOf(new Date(0))); // 'object'
console.log(typeOf(NaN)); // 'number'
Each line is a surprise:
nullmeans "no value", yet it reports'object'. That is a bug from the very first version of JavaScript. Changing it would break too much existing code, so it is permanent.- Arrays and dates are objects underneath, so
typeofcan't tell them apart from{}. NaNmeans "not a number", but its type is number. It is the result of maths that went wrong, like0 / 0.
Step 4: a more precise answer
Every built-in object carries a hidden label, which shows up when you turn it into text with Object.prototype.toString. You call it with .call(value), which runs the method with value as the object it works on:
console.log(Object.prototype.toString.call([])); // '[object Array]'
console.log(Object.prototype.toString.call(null)); // '[object Null]'
The useful part is the word after [object . slice(8, -1) cuts it out: it skips the first 8 characters ([object including the space) and drops the last one (]):
const preciseType = (value) => Object.prototype.toString.call(value).slice(8, -1);
console.log(preciseType(null)); // 'Null'
console.log(preciseType([])); // 'Array'
console.log(preciseType(new Date(0))); // 'Date'
console.log(preciseType(/x/)); // 'RegExp'
console.log(preciseType({})); // 'Object'
Now null, arrays, dates and regular expressions all get their own names, and a plain object is still 'Object'.
Step 5: the simple test for arrays
Arrays come up so often that JavaScript has a dedicated check:
console.log(Array.isArray([])); // true
console.log(Array.isArray({})); // false
When the only question is "is this an array?", Array.isArray is the clearest way to ask it.
The full solution
The panel has typeOf and preciseType. It runs both on fourteen different values, from {} to NaN, printing one row per value, then lists every distinct typeof result it saw and counts them. Press Run and check that the count is eight.
const typeOf = (value) => typeof value;
// A more useful answer: the internal tag, which typeof cannot give you.
const preciseType = (value) => Object.prototype.toString.call(value).slice(8, -1);
const samples = [{}, true, () => {}, 1, 'text', undefined, 1n, Symbol('s'),
null, [], new Date(0), /x/, new Map(), NaN];
const seen = new Set(samples.map(typeOf));
for (const v of samples) {
const shown = typeof v === 'symbol' ? 'Symbol(s)' : typeof v === 'bigint' ? '1n' : JSON.stringify(v) ?? String(v);
console.log(String(shown).padEnd(12), 'typeof:', typeOf(v).padEnd(10), 'precise:', preciseType(v));
}
console.log('--- older references say six. the real list is: ---');
console.log([...seen].sort().join(', '));
console.log('count:', seen.size);
Output
20 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 20 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('an object', typeOf({}), 'object');
test('a boolean', typeOf(true), 'boolean');
test('a function', typeOf(() => {}), 'function');
test('a number', typeOf(1), 'number');
test('a string', typeOf('text'), 'string');
test('undefined', typeOf(undefined), 'undefined');
test('bigint, which the source does not list', typeOf(1n), 'bigint');
test('symbol, which it does not either', typeOf(Symbol('s')), 'symbol');
test('so there are eight results, not six', new Set(['object', 'boolean', 'function', 'number', 'string', 'undefined', 'bigint', 'symbol']).size, 8);
test('null reports as object, which is a 1995 bug', typeOf(null), 'object');
test('an array also reports as object', typeOf([]), 'object');
test('so does a date', typeOf(new Date(0)), 'object');
test('and NaN reports as a number', typeOf(NaN), 'number');
test('the precise version separates null out', preciseType(null), 'Null');
test('and arrays', preciseType([]), 'Array');
test('and dates', preciseType(new Date(0)), 'Date');
test('and regular expressions', preciseType(/x/), 'RegExp');
test('and Maps', preciseType(new Map()), 'Map');
test('while still calling a plain object an Object', preciseType({}), 'Object');
test('Array.isArray is the reliable array test', [Array.isArray([]), Array.isArray({})], [true, false]);
The six-result claim is out of date, and the assertion counting eight rather than six is the exercise. symbol arrived with ES6 and bigint later still, so any list written from an older reference is short by two.
typeof is also coarse in a way that matters. It reports 'object' for null, for arrays, for dates and for Maps, which is almost never the answer you wanted. typeof null === 'object' is a genuine bug in the first implementation; fixing it was proposed and rejected because too much code depends on it, so it is permanent.
Object.prototype.toString.call(v).slice(8, -1) gives 'Null', 'Array', 'Date', 'RegExp', 'Map' and so on. It is the one check that is never fooled, and it is worth keeping as a two-line helper. For arrays specifically, Array.isArray is clearer and works across realms.
Common mistakes
- Checking for objects with
typeof value === 'object'. It is alsotruefornulland arrays. Addvalue !== null, or usepreciseType. - Writing
typeof(value)and thinking it is a function call. It works, buttypeofis an operator; the brackets just group the value. - Expecting
typeof NaNto be something other than'number'. To spotNaN, useNumber.isNaN(value).
Try it yourself
- Run
preciseTypeonnew Map(),new Set()andPromise.resolve(). What names come back? - Write
isPlainObject(value)that returnstrueonly whenpreciseType(value) === 'Object'. - What does
typeof typeof 42give? Work it out before you run it.