Check if a value is an object in JavaScript
Intermediate · 3 min read
Before you read a property like value.plate, you often need to know that value is an object. If it is a number you get undefined, and if it is null the program crashes. Config loaders, API handlers and deep-copy helpers all start with this check.
In this tutorial you will write isObject and see the two places where typeof gives a misleading answer. You should know what an object and an array are. Everything else is explained as we go.
Primitives and objects
Every value in JavaScript is one of two kinds. Primitives are simple values: strings, numbers, booleans, null, undefined, plus two rarer ones, BigInt and Symbol. Everything else is an object: plain {} objects, arrays, dates, regular expressions, maps, and functions too.
The main difference: an object can hold properties, and a primitive can't keep any.
const settings = {};
settings.theme = 'dark';
console.log(settings.theme); // dark
const list = [1, 2];
list.label = 'pair';
console.log(list.label); // pair
What typeof says
typeof names a value's type. For objects it mostly says 'object', with two surprises:
console.log(typeof {}); // object
console.log(typeof []); // object
console.log(typeof new Date()); // object
console.log(typeof null); // object
console.log(typeof function () {}); // function
null is a primitive, but typeof calls it 'object'. That is a bug from the first version of JavaScript that was never fixed. And a function is an object, but typeof calls it 'function'.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
6 Is the value an object?
fairCheck whether a value is an object. Two traps: typeof null is 'object', and a function is an object even though typeof says otherwise.
Stuck? Three hints, smallest first
- 1. Rule out
nullexplicitly, becausetypeof null === ‘object’. - 2. Arrays, dates and regular expressions are all objects. Decide whether you want them.
- 3.
typeof fnis‘function’, but a function really is an object — you can put properties on it.
Step 1: the naive check
The first version most people write trusts typeof:
const isObjectNaive = (v) => typeof v === 'object';
console.log(isObjectNaive({})); // true
console.log(isObjectNaive(null)); // true
null gets through. Now imagine the next line reads a property:
const v = null;
try {
console.log(v.plate);
} catch (err) {
console.log(err.name); // TypeError
}
Reading a property of null throws a TypeError. The check was supposed to prevent exactly that.
Step 2: rule out null
Add v !== null to the check. && means both parts must be true:
const isNonFunctionObject = (v) => typeof v === 'object' && v !== null;
console.log(isNonFunctionObject({})); // true
console.log(isNonFunctionObject([])); // true
console.log(isNonFunctionObject(null)); // false
console.log(isNonFunctionObject(42)); // false
console.log(isNonFunctionObject('bus')); // false
This is the standard guard you will see in many codebases. The null half is not optional.
Step 3: let functions in
A function really is an object. You can put properties on it, just like on {}:
function fare() {}
fare.currency = 'NGN';
console.log(typeof fare); // function
console.log(fare.currency); // NGN
If "object" means "something that can hold properties", functions should count. || means "or", so we accept either case:
const isObject = (v) => (typeof v === 'object' && v !== null) || typeof v === 'function';
function fare() {}
console.log(isObject({})); // true
console.log(isObject(new Map())); // true
console.log(isObject(fare)); // true
console.log(isObject(null)); // false
console.log(isObject(undefined)); // false
Which version you want depends on the job. If you are about to list an object's keys or turn it into JSON, you probably don't want functions, so use the Step 2 check.
Step 4: telling objects apart
Both checks treat arrays, dates and plain objects the same. When you need to know which kind you have, two tools help.
Array.isArray tells arrays apart, and it isn't fooled by an object that just has a length:
console.log(Array.isArray([])); // true
console.log(Array.isArray({ length: 0 })); // false
The tag check names the kind of object. Object.prototype.toString.call(v) gives a string like '[object Array]', and .slice(8, -1) keeps the middle word:
const tag = (v) => Object.prototype.toString.call(v).slice(8, -1);
console.log([{}, [], new Date(), /x/].map(tag)); // [ 'Object', 'Array', 'Date', 'RegExp' ]
console.log(tag(null)); // Null
The full solution
The panel has both checks and the fare function with its property. Press Run to see what typeof and the tag say about each kind of value.
const tag = (v) => Object.prototype.toString.call(v).slice(8, -1);
// Anything you can hold properties on, functions included.
const isObject = (v) => (typeof v === 'object' && v !== null) || typeof v === 'function';
// Objects only, no functions.
const isNonFunctionObject = (v) => typeof v === 'object' && v !== null;
// Proof that a function is an object: it can carry properties.
function fare() {}
fare.currency = 'NGN';
console.log('typeof {} :', typeof {});
console.log('typeof [] :', typeof [], '<- also "object"');
console.log('typeof null :', typeof null, '<- also "object", and it is not one');
console.log('typeof fare :', typeof fare, '<- "function", but it IS an object');
console.log('a property on a function:', fare.currency);
console.log('--- the tag tells them apart ---');
for (const v of [{}, [], null, new Date(), /x/, fare, new Map()]) {
console.log(tag(v).padEnd(10), 'isObject:', isObject(v));
}
Output
17 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 17 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a plain object', isObject({}), true);
test('an array', isObject([]), true);
test('a date', isObject(new Date()), true);
test('a regular expression', isObject(/x/), true);
test('a Map', isObject(new Map()), true);
test('a function counts as an object', isObject(fare), true);
test('because it can carry properties', fare.currency, 'NGN');
test('null does NOT count', isObject(null), false);
test('even though typeof says object', typeof null, 'object');
test('a number is not an object', isObject(42), false);
test('nor a string', isObject('bus'), false);
test('nor undefined', isObject(undefined), false);
test('the stricter check excludes functions', isNonFunctionObject(fare), false);
test('but still accepts an array', isNonFunctionObject([]), true);
test('Array.isArray separates arrays out', Array.isArray([]), true);
test('and is not fooled by an array-like object', Array.isArray({ length: 0 }), false);
test('the tag distinguishes what typeof cannot', [{}, [], new Date(), /x/].map(tag), ['Object', 'Array', 'Date', 'RegExp']);
typeof v === 'object' && v !== null is the standard guard, and the null half is not optional — without it, isObject(null) returns true and the next line that reads a property throws. Whether functions should count depends on the question: they are objects (the fare.currency assertion proves it), but if you are about to enumerate keys or serialise the value, you probably want them excluded. Array.isArray is the one built-in worth remembering; it is reliable and it works across realms.
Common mistakes
- Leaving out
v !== null.typeof nullis'object', sonullgets through and the next property read throws. - Expecting
typeofto say'array'. It says'object'. UseArray.isArray. - Forgetting that functions are objects. Decide whether your check should accept them, and write the check to match.
Try it yourself
- Write
isPrimitive(v)as the opposite ofisObject, and test it withnulland a function. - Write
safeGet(obj, key)that returnsundefinedinstead of throwing whenobjisn't an object. - Run the tag on
new Set(),Promise.resolve()andMath, and predict each answer first.