Hone

Lessons · JavaScript · null vs undefined vs empty

Does it have a value

x != null is true for every value except null and undefined. if (x) also rejects 0, '' and false, which is usually not what you meant.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

A quantity of 0, an empty search string, an unchecked box: all real values, all thrown away by if (x). The wrong check hides real data, and the missing check is where 'cannot read properties of undefined' comes from.

How to think about it

For 'is it missing', write x == null or x === undefined. For 'is it usable', test the property you need: x.length > 0, x > 0. Reading down into data that might not be there, write a?.b?.c so a missing link gives undefined instead of a crash.

Worked example

let x = null;
Missing.
console.log(x == null, x === undefined);
true false: == null catches null and undefined together.
x = 0;
A real value.
console.log(x == null, !x);
false true: 0 is present, but if (!x) would treat it as missing.
console.log(x != null ? "has a value" : "missing");
has a value.
const user = { name: "Ada" };
A record with no address at all.
console.log(user?.address?.city);
undefined: ?. stops at the missing link instead of throwing.

Your turn

Use the value only when it is present.

if (value  null) { use(value); }

The trap

if (x) rejects 0, '' and false along with null and undefined. Ask the question you mean: x != null.

Practise null vs undefined vs empty on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.