Differences Between Falsy and Nullish Values in JavaScript

Hero image for Differences Between Falsy and Nullish Values in JavaScript. Image by Evan Buchholz.
Hero image for 'Differences Between Falsy and Nullish Values in JavaScript.' Image by Evan Buchholz.

JavaScript is a versatile and dynamic language that often requires developers to handle various types of values. Two common concepts to be familiar with are "falsy" and "nullish" values. These terms describe different scenarios when working with conditionals, expressions, and default values.


Falsy Values

In JavaScript, falsy values are those that are considered false when coerced into a Boolean context and are automatically converted to false in conditions that require a Boolean result.

Here are a few examples of falsy values:

  • false
  • 0
  • '' (an empty string)
  • null
  • undefined
  • NaN (Not a Number)

The reason it's important to understand the distinction is that falsy values can lead to unintended behaviour if not handled properly in conditionals. For example:

const divideNumbers = (a: number, b: number): number => a / b;const printResult = (result: number) => {  if (result) {    console.log(`Result: ${result}`);  } else {    console.log('No result available.');  }};printResult(divideNumbers(10, 0));  //=> No result available.

In this example, we have a function divideNumbers which calculates the result of dividing two numbers. We then have a function printResult that prints the result if it exists.

When we call divideNumbers(10, 0), it attempts to divide 10 by 0, resulting in Infinity. However, Infinity is considered a truthy value in JavaScript, so the if (result) condition in the printResult function evaluates to true, and it logs Result: Infinity instead of No result available.

As you might appreciate, this behaviour could be unexpected as it suggests that the division succeeded when in reality it produced an infinite result, which might not be the intended behaviour. To avoid this, we need to handle such scenarios explicitly, checking for specific invalid results or using different errorhandling mechanisms.


Nullish Values

Nullish values are a more specific subset of falsy values. In contrast to falsy values, nullish values are only considered false in a Boolean context when they are null or undefined. Any other falsy value, like 0, false, or '', is not considered nullish.

To handle nullish values and avoid potential bugs, we can use the nullish coalescing operator (??). This operator allows us to set default values when encountering null or undefined values.

const printName = (name: string | null) => {  const defaultName = 'Anonymous';  const finalName = name ?? defaultName;  console.log(`Hello, ${finalName}!`);};printName(null);  //=> Hello, Anonymous!printName('John');  //=> Hello, John!

In this example, the printName function uses the nullish coalescing operator to set a default name of Anonymous when the provided name is null or undefined.


The Difference in Practice

The distinction between falsy and nullish values becomes crucial when handling default values or performing conditional checks.

Consider the following example:

const fetchUserData = (user: any) => {  const username = user.username || 'DefaultUser';  const email = user.email ?? 'default@example.com';  console.log(`Username: ${username}, Email: ${email}`);};const user1 = { username: '', email: '' };const user2 = { username: null, email: null };const user3 = { username: 'Sophie', email: 'sophie@example.com' };fetchUserData(user1);  //=> Username: DefaultUser, Email: default@example.comfetchUserData(user2);  //=> Username: DefaultUser, Email: default@example.comfetchUserData(user3);  //=> Username: Sophie, Email: sophie@example.com

Here, we use the logical OR (||) to set default values for username and the nullish coalescing operator (??) to set default values for email.

When user1 and user2 have falsy values for username and email, the logical OR will use the default values as they are considered falsy. However, when user3 contains legitimate values, they are preserved, thanks to the nullish coalescing operator.


Wrapping‑Up

Understanding the differences between falsy and nullish values is essential for writing robust and bugfree JavaScript code. Falsy values are a broader category that includes 0, '', null, undefined, NaN, and false. On the other hand, nullish values specifically refer to null and undefined.


Categories:

  1. ES6
  2. JavaScript
  3. TypeScript