Null and Falsey Checking in JavaScript
All in all there are two types of important null or falsey checking that you’ll be using in JavaScript:
- Logical OR (||)
- Null Coalescence (??)
Both of these will help you write better and more maintainable code. And when I say null checking, I mean returning a value other than null or falsey when your variable assignment may turn out to be null or undefined.
A hypothetical situation might be retrieving a value from an asynchronous call. Maybe you decided to retrieve a user’s profile information based on a url param. What if a user enters the wrong url? This would be a situation to do some null or falsey checking and return something more useable.
Example:
// These params might look like https://example.com/:user
const userName = match.params.user;
// I want to fetch the user based on the user params in the url
// Sometimes this wouldn't return a user if the user did not exist!
const response = await fetchUserProfileFromUrlParam(userName);
// Here if my response was not successful, instead of returning undefined,
// I could return an empty object instead
const userData = response.success && response.data ?? {}
This is just a random scenario to help better understand why we might be using a null check. Let’s dive into what null coalescence and the logical OR is a little deeper.
Logical OR ( || )
- If the left side of the || is false, then it will will use the right side.
- Logical OR includes more than undefined and null. It includes 0, NaN and “” (empty strings)
- Link to MDN Docs on Logical OR ||
const value1 = '';
const myValue = value1 || 'Hello World'; // Hello World
const value2 = 0;
const myValue2 = value2 || 200; // 200
const value3 = undefined;
const myValue3 = value3 || 'Boom!'; // Boom!
const value4 = null;
const myValue4 = value4 || await myAsyncCall(); // data from async call
Null Coalescence ( ?? )
- returns the right side if the left side is null or undefined
- Link to MDN Docs on Nullish Coalescing Operator
const value1 = null;
const myValue1 = value1 ?? 'Hello World'; // Hello World
const myObj = {
text: 'Hello World'
}
const value2 = myObj.anotherValue; // undefined
const myValue2 = value2 ?? 'Boom!'; // boom
Thanks for reading! Stay connected with me via my Github or LinkedIn:
LinkedIn: https://www.linkedin.com/in/blakewoodjr/
😎👋🏽