Menu Home

nullish operator (??)

Hi everyone, and welcome to another nail-biting episode of Boring JavaScript! Today, we tackle the “nullish coalescing operator”, or as others like to call it, the “What What?” operator.

Don’t like to read? Then watch our video.

Whoops! I Did It Again!

The nullish coalescing operator was created to solve a particular problem in JavaScript. What problem? It’s best to show you with an example (Hint: Pay attention to lines 7 and 8):

class Animal {
	name;
	age;

	constructor (args) {
		const { name, age } = args;
		this.name = name || "";
		this.age = age || -1;
	}

	stats () {
		return `${this.name}: ${this.age === -1 ? 'Deceased.' : `${this.age} years.`}`;
	}
}

let name = "Fluffy";
let age = 2;
const myCat = new Animal({ name, age });

name = "Rover";
age = 0;
const myDog = new Animal({ name, age });

console.log(`My cat's stats: ${myCat.stats()}`);
console.log(`My dog's stats: ${myDog.stats()}`);

When you run this, the console prints out the following:

My cat's stats: Fluffy: 2 years.
My dog's stats: Rover: Deceased.

What gives? We set the dog’s age to 0 (he’s just a puppy) in Line 21.

What happened is due to the “or” operator we used in Line 8. Using “or” here ( || ) tells JavaScript to take the first expression (age) unless it is “falsey”, in which case take the second expression “-1”. The number “0” is a falsey value – therefore, the second expression was taken instead.

Of course, this is not what we want. We need a way to let the class know that “0” is a valid number. Enter the nullish coalescing operator.

We’re Defining Undefined

The nullish coalescing operator works in the same way as the “or” operator above – except that it will only default to the second expression when the first expression is “null” or “undefined”. Any other value – like 0 or “” – will be accepted as a valid value.

The nullish coalescing operator uses two question marks – ?? – so let’s change lines 7 and 8 above to use the operator and see what happens.

class Animal {
	name;
	age;

	constructor (args) {
		const { name, age } = args;
		this.name = name ?? "";
		this.age = age ?? -1;
	}

	stats () {
		return `${this.name}: ${this.age === -1 ? 'Deceased.' : `${this.age} years.`}`;
	}
}

let name = "Fluffy";
let age = 2;
const myCat = new Animal({ name, age });

name = "Rover";
age = 0;
const myDog = new Animal({ name, age });

console.log(`My cat's stats: ${myCat.stats()}`);
console.log(`My dog's stats: ${myDog.stats()}`);

Exact same code, except that now we are using “??” instead of “||”. And the results?

My cat's stats: Fluffy: 2 years.
My dog's stats: Rover: 0 years.

And, yes, that is exactly what we want. The nullish coalescing operator should be used in place of the “or” operator when you want to default to another value if and only if the tested value is null or undefined.

The Video

As always, here is a video on the subject.

Shameless Plug

Catch us all over the ‘web!

Check out all our videos at: https://www.boringjavascript.com
Check out everything at: https://www.thevirtuoid.com

Facebook: https://www.facebook.com/TheVirtuoid
Twitter: https://twitter.com/TheVirtuoid
YouTube: https://www.youtube.com/channel/UCKZ7CV6fI7xlh7zIE9TWqgw

Categories: Boring JavaScript Javascript

Tagged as:

thevirtuoid

Web Tinkerer. No, not like Tinkerbell.

Creator of the game Virtuoid. Boring JavaScript. Visit us at thevirtuoid.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: