How to Check for Null Values in JavaScript

How to check for null in JavaScript with strict and loose equality, plus nullish coalescing, optional chaining, and the mistakes to avoid.

Mahzaib MirzaMahzaib MirzaJune 14, 20233 min read0 comments
How to Check for Null Values in JavaScript

To check whether a value is null in JavaScript, use strict equality: value === null. To check for null or undefined together, use value == null. Avoid if (!value) for this, because it is also true for 0, empty strings, false and NaN.

let value = null;

console.log(value === null); // true
console.log(value == null);  // true  (null or undefined)

value = undefined;

console.log(value === null); // false
console.log(value == null);  // true

null vs undefined

undefined means a variable has not been given a value, or a property does not exist. null is a value you assign on purpose to mean "nothing here". They are different values, and the strict equality operator treats them as different:

console.log(null === undefined); // false
console.log(null == undefined);  // true

Strict equality: === null

Use === null when you only care about null, for example a value returned from an API or a database where null has a specific meaning:

const user = JSON.parse('{"name": "Sam", "phone": null}');

if (user.phone === null) {
  console.log('No phone number on file');
}

Loose equality: == null

== null is the one place where loose equality is widely accepted. It is true for null and undefined and for nothing else:

function isNil(value) {
  return value == null;
}

isNil(null);      // true
isNil(undefined); // true
isNil(0);         // false
isNil('');        // false
isNil(false);     // false

Do not use typeof to test for null

typeof null returns 'object', a long-standing quirk of the language, so typeof cannot tell null from an object:

console.log(typeof null);      // 'object'
console.log(typeof undefined); // 'undefined'
console.log(typeof {});        // 'object'

If you want to know whether something is a real object, rule out null first:

const isObject = (value) => typeof value === 'object' && value !== null;

isObject({});   // true
isObject(null); // false

The falsy-value trap

if (!value) runs for every falsy value: null, undefined, 0, '', false and NaN. That is a bug when 0 or an empty string is a valid value:

const quantity = 0;

if (!quantity) {
  console.log('Treated as missing, but 0 is a real quantity');
}

if (quantity === null || quantity === undefined) {
  console.log('This does not run, which is correct');
}

Provide a default: the ?? operator

The nullish coalescing operator ?? returns its right side only when the left side is null or undefined. The older || operator replaces every falsy value:

const count = 0;
const label = '';

console.log(count || 10);  // 10  - the real 0 was replaced
console.log(count ?? 10);  // 0   - kept

console.log(label || 'none'); // 'none'
console.log(label ?? 'none'); // ''
console.log(null ?? 'none');  // 'none'

Read a property safely: the ?. operator

Optional chaining stops and returns undefined if the value before it is null or undefined, instead of throwing:

const user = { profile: null };

console.log(user.profile?.email);       // undefined
console.log(user.profile?.email ?? ''); // ''

// Without ?. this throws: TypeError: Cannot read properties of null
// console.log(user.profile.email);

Default parameters do not replace null

A default parameter is used only when the argument is undefined. Passing null does not trigger it:

function greet(name = 'friend') {
  return 'Hello, ' + name;
}

console.log(greet(undefined)); // 'Hello, friend'
console.log(greet(null));      // 'Hello, null'

If null is possible, handle it inside the function with ??.

Remove null values from an array

const values = [1, null, 2, undefined, 0, 3];

console.log(values.filter((v) => v !== null));
// [1, 2, undefined, 0, 3]  - removes only null

console.log(values.filter((v) => v != null));
// [1, 2, 0, 3]  - removes null and undefined, keeps 0

To check whether an array itself is missing or empty, see how to check if an array is empty or null in JavaScript.

In TypeScript

With strictNullChecks on, which strict mode enables, a type that can be null must be written out, and the compiler makes you check before use:

function shout(text: string | null): string {
  if (text === null) {
    return '';
  }
  return text.toUpperCase(); // text is string here
}

Which check should I use?

  • === null: only null counts as missing.

  • == null: null and undefined both count as missing.

  • ??: you want a default for null or undefined but must keep 0 and empty strings.

  • ?.: you are reading a property that might not exist.

  • !value: only when every falsy value really should count as missing.

Frequently asked questions

How do I check if a variable is null or undefined?

Use value == null. It is true for both null and undefined, and for no other value.

Why does typeof null return object?

It is a historical quirk of JavaScript that was never changed. Use value === null to test for it.

What is the difference between || and ??

|| returns the right side for any falsy left side. ?? returns it only when the left side is null or undefined.

Share:
Mahzaib Mirza

Written by

Mahzaib Mirza

Software developer & Founder of Coders Vibe.

Related Posts

Liked this post?

Get the next one in your inbox the moment it's published. No spam, unsubscribe anytime.

0 Comments

Leave a comment