Check if a value is null in JavaScript
Beginner · 3 min read
JavaScript has two values that mean "nothing here": null and undefined. They look alike, but they say different things. null means "empty on purpose", like a bus with no driver assigned yet. undefined means "never set", like a field nobody filled in.
In this tutorial you will write isNull, a check that catches null and nothing else. You will see why typeof can't do it, when to use === and when ==, and how the two empty values behave differently. You need to know what an object and a property are.
Two kinds of empty
Here is a bus record. The driver is set to null on purpose. There is no conductor property at all:
const bus = { plate: 'LAG-441-XA', driver: null };
console.log(bus.driver); // null
console.log(bus.conductor); // undefined
console.log('driver' in bus); // true
console.log('conductor' in bus); // false
Reading a property that doesn't exist gives undefined. The in operator asks whether the key exists. It shows the real difference: driver is there and empty, conductor was never there.
typeof null is 'object'
You might reach for typeof, which names a value's type:
console.log(typeof undefined); // undefined
console.log(typeof null); // object
console.log(typeof {}); // object
typeof null says 'object'. This was a bug in the very first version of JavaScript. Fixing it was proposed, but too much existing code depends on it, so it stays. It means typeof can't tell null from a real object.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
4 Is the value null?
easyDetect null specifically, and not undefined. The obvious typeof approach cannot do it.
Stuck? Three hints, smallest first
- 1.
typeof nullis‘object’. This is a bug from 1995 that can never be fixed. - 2.
v === nullis the whole check. Use===, becausenull == undefinedis true. - 3. To catch both at once,
v == nullis the idiomatic shorthand.
Step 1: compare with ===
The whole check is one comparison. === (strict equality) is only true when both sides are the same type and the same value:
const isNull = (v) => v === null;
console.log(isNull(null)); // true
console.log(isNull(undefined)); // false
console.log(isNull(0)); // false
console.log(isNull('')); // false
console.log(isNull({})); // false
0 and '' are "empty-ish", but they are real values, and isNull correctly refuses them.
Step 2: the == wrong turn
There is also ==, loose equality. It converts values before comparing, and it has a special rule for the two empty values:
console.log(null == undefined); // true
console.log(null === undefined); // false
So a check written with == quietly accepts undefined as well. If you asked for "only null", that is a bug.
Step 3: when you want both
Often you don't care which kind of empty you have. You just want to know "is there a value here?". That is the one place where == is the usual choice:
const isNullish = (v) => v == null;
const isUndefined = (v) => v === undefined;
console.log(isNullish(null)); // true
console.log(isNullish(undefined)); // true
console.log(isNullish(0)); // false
console.log(isNullish('')); // false
console.log(isNullish(false)); // false
console.log(isNullish(NaN)); // false
v == null is true for null and undefined, and false for everything else, including 0, '' and false. Some style guides allow == only for this one case. "Nullish" is the name for "null or undefined".
Step 4: the tag check knows better
If you need a type name that gets null right, the tag check from the earlier exercises does:
const tag = (v) => Object.prototype.toString.call(v).slice(8, -1);
console.log(tag(null)); // Null
console.log(tag(undefined)); // Undefined
console.log(tag({})); // Object
Object.prototype.toString.call(v) describes null as '[object Null]', and .slice(8, -1) cuts out 'Null'.
Step 5: they behave differently in JSON
The difference between the two empties isn't just a matter of words. JSON.stringify, which turns data into text for sending or saving, treats them differently:
console.log(JSON.stringify({ a: null, b: undefined })); // {"a":null}
It keeps null and drops the undefined key completely. So if you save data as JSON and load it again, a null field comes back, but an undefined field is gone.
The full solution
The panel has isNull, isNullish and isUndefined, plus the bus record from the start. Press Run to see how typeof, the tag, == and JSON treat each empty value.
const tag = (v) => Object.prototype.toString.call(v).slice(8, -1);
const isNull = (v) => v === null; // strict: only null
const isNullish = (v) => v == null; // loose: null OR undefined
const isUndefined = (v) => v === undefined;
console.log('typeof null :', typeof null, '<- the famous mistake');
console.log('tag(null) :', tag(null), '<- the tag gets it right');
console.log('null == undefined:', null == undefined, '<- loose equality merges them');
console.log('null === undefined:', null === undefined);
console.log('--- and they behave differently ---');
const bus = { plate: 'LAG-441-XA', driver: null };
console.log('a null property :', bus.driver, '(deliberately empty)');
console.log('a missing property:', bus.conductor, '(never set)');
console.log("'driver' in bus :", 'driver' in bus);
console.log("'conductor' in bus:", 'conductor' in bus);
console.log('JSON keeps null, drops undefined:', JSON.stringify({ a: null, b: undefined }));
Output
15 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 15 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('null is null', isNull(null), true);
test('undefined is not null', isNull(undefined), false);
test('0 is not null', isNull(0), false);
test('the empty string is not null', isNull(''), false);
test('typeof null is "object", so typeof cannot be used', typeof null, 'object');
test('the tag check knows better', tag(null), 'Null');
test('loose equality merges null and undefined', null == undefined, true);
test('strict equality does not', null === undefined, false);
test('the nullish check catches both', [null, undefined].every(isNullish), true);
test('and nothing else', [0, '', false, NaN].some(isNullish), false);
test('a deliberately empty property is null', isNull(bus.driver), true);
test('a property that was never set is undefined', isUndefined(bus.conductor), true);
test('but the key exists for the null one', 'driver' in bus, true);
test('and not for the other', 'conductor' in bus, false);
test('JSON.stringify keeps null and drops undefined', JSON.stringify({ a: null, b: undefined }), '{"a":null}');
typeof null === 'object' is a genuine bug in the first JavaScript implementation. A proposal to fix it was rejected because too much existing code depends on it, so it is permanent. Practically, keep the distinction: null means "empty on purpose", undefined means "never set". JSON.stringify takes that seriously — it keeps null and silently removes undefined, so a round-trip through JSON loses one and not the other.
Common mistakes
- Using
typeof v === 'object'to findnull. It is alsotruefor every object. Compare withv === null. - Using
==when you meant onlynull.null == undefinedistrue. Use===unless you want both. - Using
!vto mean "missing". That also catches0,''andfalse, which are real values. Usev == null.
Try it yourself
- Write
hasValue(v)that returnstruefor anything exceptnullandundefined, and test it with0. - Write
countNulls(obj)that counts how many properties of an object are exactlynull. - Run
JSON.parse(JSON.stringify({ a: null, b: undefined }))and check which keys survive.