Hey there! Have you ever been frustrated trying to handle null or undefined values in your JavaScript code? Nullish coalescing is a new feature that helps make that a whole lot easier. In this post, we’ll explain nullish coalescing.
That means simple terms, fun examples, and no complicated jargon. By the end, you’ll be writing clean, concise JS code in no time.
So what exactly is nullish coalescing? Basically, it’s a short, simple way to provide a default value when something is null or undefined. Instead of having messy nested ternaries or logical OR statements, you can use the double question mark operator (??) to coalesce to a default.
Sound confusing? Don’t worry, we’ll show you how it works with some easy-to-follow examples. Buckle up, this is going to be a fun ride!
Have you ever gotten stuck dealing with null values in JavaScript? I know I have. Well, my friend, let me introduce you to the nullish coalescing operator (??). This little guy is going to make your life so much easier.
So what exactly is the nullish coalescing operator? Basically, it's a shortcut to provide a default value when something could be null or undefined. Instead of writing:
let name = obj.name || 'default name';
You can now simply write:
let name = obj.name ?? 'default name';
The ?? operator will return the left side if it's not nullish (meaning null or undefined), otherwise, it will return the right side. So in the example above, if obj.name
is not null or undefined, name will be set to obj.name
. But if obj.name
is null or undefined, name will be 'default name'.
Pretty handy, right? Some other examples:
let age = ageInput ?? 25; // Sets age to ageInput if not nullish, otherwise 25
let email = user.email ?? 'no email provided';
let hobbies = obj.hobbies ?? []; // Sets hobbies to obj.hobbies if not nullish, otherwise an empty array
I hope this helps simplify some of your conditional logic in JavaScript.
Have you ever gone to pay for something, only to realize you're a few bucks short? We've all been there. Nullish coalescing is like finding a few extra dollars in your pocket so you can actually afford what you want to buy.
Let's say you head to your favorite coffee shop for your usual morning brew. You go up to the counter with $3 in your hand, ready to order. But when the barista tells you your total, it comes out to $3.50 after tax.
Nullish coalescing is like suddenly remembering you have another dollar in your pocket, so you can still get your coffee. Phew!
In JavaScript, nullish coalescing is a way to provide a default value in case something resolves to null or undefined. For example, say you have a function that may or may not return a value:
function getCoffeePrice() {
// Returns $3.50 or undefined
}
let price = getCoffeePrice() ?? '$3.50';
Here, if getCoffeePrice()
returns undefined, price
will be '$3.50'
by default thanks to the ??
nullish coalescing operator. So you're guaranteed to have a price for your coffee either way.
Nullish coalescing allows your code to be more resilient by providing fallback default values when variables are null or undefined. Just like finding that extra dollar in your pocket at the coffee shop, it ensures you have what you need to complete the transaction. Pretty handy, right?
Now you can rest easy knowing you understand nullish coalescing like a pro. Happy coding and enjoy your coffee!
The nullish coalescing operator (??) returns its left operand if it's not nullish; otherwise, it returns its right operand.
Confused? Let's break that down. A "nullish" value is either null or undefined. So the ??
operator checks if the left value is nullish, and if so, returns the right value instead.
For example:
const name = bob ?? 'anonymous';
This will assign the value of name to 'bob' if bob is defined. If bob is undefined or null, it will assign the string 'anonymous' instead.
Without the ?? operator, you'd have to do this:
const name = bob !== null && bob !== undefined ? bob : 'anonymous';
The ?? operator gives us a shorter, cleaner syntax to essentially do the same thing.
It can be used anywhere in JavaScript - in variables, function arguments, object properties, etc. Anywhere you'd normally use the || (or) operator for default values, you can now use ?? for a "nullish" default value.
const foo = null ?? 'default string';
// foo is 'default string'
const bar = 0 ?? 42;
// bar is 0
const qux = 0 || 42;
// qux is 42 - || returns first truthy value
function doSomething(x = 0) {
x = x ?? 10;
// If x is nullish, set default of 10
console.log(x);
}
doSomething(null); // Prints 10
doSomething(5); // Prints 5
I hope this helps explain the nullish coalescing operator!
The OR (||) operator works by returning the first truthy value it encounters. If both values are falsy, it will return the last value. For example:
let name = null;
let user = name || 'John'; // user is 'John'
Here, name
is null (falsy), so user
gets the second value, 'John'.
The Nullish Coalescing Operator (??) was introduced in ES2020 and is a bit smarter than OR (||). It will return the first defined value (not null/undefined). So if the first value is an empty string, 0, or false, it will return that value. For example:
let name = '';
let user = name ?? 'John'; // user is ''
Here, name
is an empty string, so user
gets name
(the first defined value).
The Nullish Coalescing Operator allows us to provide default values in a cleaner way. We can set default values for null/undefined values without worrying about falsy values like 0, empty strings, false, etc.
For example, say we have a function that returns a user's age, but sometimes the age is null:
function getAge() {
return age; // could be null
}
let userAge = getAge() || 30; // Uses OR, not ideal
Here, if age
is 0, '', or false, userAge
would incorrectly be 30.
Using the Nullish Coalescing Operator fixes this:
let userAge = getAge() ?? 30; // Uses ??
Now, userAge
will only be 30 if age
is null or undefined. Any other falsy value like 0 will be used.
So in summary, use the Nullish Coalescing Operator (??) instead of OR (||) when you want to provide a default value for null/undefined, but not for falsy values like 0, empty strings, or false.
Your code will be cleaner and less prone to bugs!
So you've heard about this fancy new Nullish Coalescing operator (??) in JavaScript and have some questions. No worries, I've got you covered!
The || (OR) operator will return the right operand if the left operand is falsy (false, 0, empty string, null, undefined, NaN).
The ?? (Nullish Coalescing) operator will only return the right operand if the left operand is null or undefined.
So the key difference is that ?? considers 0 and empty strings to be valid values, whereas || does not.
Use ??
when you want to provide a default value for null or undefined, but consider 0 and empty strings to be valid values.
Use || when you want to provide a fallback for any "falsy" value.
Hope this helps clear up some of those burning questions you had about the Nullish Coalescing operator! Let me know if you have any other questions.
Now you know all about nullish coalescing and how it works in JavaScript. Pretty simple, right? This little operator can save you time and make your code cleaner by providing default values in a concise way.
So go forth and coalesce nullish values to your heart's content! You're well on your way to mastering modern JavaScript features.
Happy Coding!