Null fallback

2 snippets across 2 stacks - JavaScript, SQL

JSJavaScript

Nullish Coalescing (??)

JS · Data Types
Syntax
value ?? fallback
Example
const inputCount = 0;
console.log(inputCount || 10);  // 10 (wrong!)
console.log(inputCount ?? 10);  // 0  (correct)

const label = null;
console.log(label ?? "Untitled");
Output
10
0
"Untitled"

Note Only triggers on null/undefined, unlike || which triggers on all falsy values (0, "", false, NaN). Use ?? when 0 or empty string are valid values.

SQLSQL

COALESCE

SQL · String Functions
Syntax
COALESCE(value1, value2, ..., default)
Example
SELECT
  first_name,
  COALESCE(nickname, first_name) AS display_name,
  COALESCE(phone, email, 'No contact') AS primary_contact
FROM users;
Output
-- Returns the first non-NULL value from the list

Note COALESCE accepts any number of arguments and returns the first non-NULL. It is ANSI standard and works everywhere. Use it for NULL fallback chains. It is NOT specific to strings - works with any data type.

Frequently asked questions

How does JavaScript handle null fallback?
This task is covered in 2 stacks on this page: JavaScript, SQL. The "Nullish Coalescing (??)" snippet in JavaScript uses `value ?? fallback`.
Which code does the JavaScript example use?
The "Nullish Coalescing (??)" snippet uses `value ?? fallback`, from the Data Types section of the JavaScript cheat sheet.
Which stacks cover "null fallback" on this page?
JavaScript, SQL. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Nullish Coalescing (??)": Only triggers on null/undefined, unlike || which triggers on all falsy values (0, "", false, NaN). Use ?? when 0 or empty string are valid values.