whatstheoutput_

#99: ?? vs || with 0 and empty string

Topic: misc · Difficulty: ★

const a = 0;
const b = '';
console.log(a || 'default', a ?? 'default');
console.log(b || 'default', b ?? 'default');

Output

default 0
default 

Why

|| falls through to its right-hand side whenever the left side is falsy — and 0 and '' are both falsy, along with false, NaN, null, and undefined. ?? is stricter: it only falls through when the left side is specifically null or undefined. Since 0 and '' are falsy but not nullish, `a || 'default'` and `b || 'default'` both replace them with 'default', while `a ?? 'default'` keeps 0 and `b ?? 'default'` keeps the empty string exactly as they were.

More misc puzzles

Play today's puzzle →