← Back to list

That Time I Confused a ? a : b with a ?? b in JavaScript

Learn the difference between the ternary operator and nullish coalescing. Understand nullish vs falsy with examples and a cheat sheet.

Leisure Rife · 2025-08-24 10:22 · 0 claps · 1.9 min read
#ternary-operator #javascript #nullish-coalescing #javascript-tips #javascript-development
Open on Medium ↗
Wiki topics: 🌐 · Web Development

The Difference Between the Ternary Operator (?:) and the Nullish Coalescing Operator (??) in JavaScript

Introduction

At first, I thought a ? a : b had the same meaning as a ?? b.

But I was wrong.

This article explains the difference between checking for nullish values and checking for falsy values in JavaScript. It also shows which expressions are evaluated as nullish and which as falsy.

It’s also a cheat sheet to remind myself which condition is being used while coding.

Example

For nullish logic, only null and undefined are considered nullish. So in x = a ?? b, the value of x will be a unless a is null or undefined. For example: if a = ‘’ (empty string), then x = a will be ’’ .

But in x = a ? a : b, the condition checks if a is falsy. So: if a = ‘’, then x = b.

In Short: The Conclusion

In x = a ?? b, the expression checks whether a is nullish.

In x = a ? a : b, the expression checks whether a is falsy.

Cheat sheet

Nullish vs Falsy Operators

Among the commonly used operators, only ?? is nullish-aware. The others (?, ||, if(), etc.) all work with falsy logic.

Nullish vs Falsy Table

Code for Testing

const testValues = [
 { label: “null”, value: null },
 { label: “undefined”, value: undefined },
 { label: “empty string ‘’”, value: “” },
 { label: “‘hello’”, value: “hello” },
 { label: “0”, value: 0 },
 { label: “-1”, value: -1 },
 { label: "NaN", value: NaN },
 { label: “false”, value: false },
 { label: “[]”, value: [] },
 { label: “{}”, value: {} },
];

const results = testValues.map(({ label, value }) => ({
 'value of a' : label,
 'type of a': typeof value,
 'a ?? "default"': value ?? "default", // shows result of ??
 'a ? a : "default"': value ? value : "default", // shows result of ?:
 IsNullish: value == null, // true only for null/undefined
 IsFalsy: !value // true for falsy values
}));
console.table(results);

Reference


메타데이터
post_id
4f8a5bc26ae1
slug
that-time-i-confused-a-a-b-with-a-b-in-javascript-4f8a5bc26ae1
url
https://medium.com/@flytoleisure/that-time-i-confused-a-a-b-with-a-b-in-javascript-4f8a5bc26ae1
canonical_url
https://medium.com/@flytoleisure/that-time-i-confused-a-a-b-with-a-b-in-javascript-4f8a5bc26ae1
author_url
https://medium.com/@flytoleisure
status
ok
fetched_at
2026-07-14 19:59:56