Why JavaScript's || Overrides Valid Values Like 0 and false, and How ?? Fixes It
A common JavaScript bug occurs when the logical OR operator (||) is used to set default values, because it replaces every falsy value, including 0, empty strings, and false, even when a user intentionally chose them. The article explains that the nullish coalescing operator (??) only substitutes a default when a value is null or undefined, preserving legitimate falsy inputs. It shows side-by-side examples in Node.js 22 comparing both operators across different values. The piece also covers the logical assignment operators ||= and ??=, and optional chaining (?.) for safe property access. It advises checking existing code for || based defaults and warns against overusing ?. since it can hide bugs that a crash would otherwise expose.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in