How do you set a default that applies for both null and undefined in JavaScript?
Use nullish coalescing (??). For example, name = name ?? 'friend' applies the default only when name is null or undefined, not when it is 0 or empty string.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Avoiding undefined Bugs in JavaScript
Use optional chaining (?.). For example, user?.profile?.name returns undefined if any link in the chain is null or undefined, instead of throwing TypeError.
Because undefined coerces to NaN in numeric contexts. Any arithmetic with NaN produces NaN, which propagates silently. Use default parameters or validate inputs to avoid this.
Because !count catches all falsy values: undefined, null, 0, '', false, and NaN. If 0 is a valid value, use an explicit check like if (count === undefined || count === null) instead.
Still have questions?
Browse all our FAQs or reach out to our support team
