Mastering Default Values in JavaScript with the ?? Operator
Ever set a default value in JavaScript like this?
Mastering Default Values in JavaScript with the ?? Operator
the nullish coalescing (??) operator
Ever set a default value in JavaScript like this?
const port = config.port || 3000;
Seems fine, right? But what if config.port is 0? Oops — that’s a valid value for a port, but it gets replaced by 3000 because 0 is considered falsy. 😬
That’s where the nullish coalescing operator (??) steps in — a modern JavaScript feature that helps us assign defaults more safely and predictably.
So What’s the Problem with ||?
The logical OR (||) operator is often used to assign default values:
const username = userInput || 'Guest';
It works great unless the value you’re checking is a valid falsy one — like:
0false""(empty string)NaN
Example:
const score = 0;
const defaultScore = 10;
console.log(score || defaultScore); // 10 ❌ (oops - 0 is valid!)
Here, 0 is treated as falsy, so the fallback kicks in — even though 0 might be the value you wanted to keep.
Meet the ?? Operator
The nullish coalescing (??) operator works similarly to ||, but with one key difference:
It only considers
nullorundefinedas “missing” values.
Example:
const score = 0;
const defaultScore = 10;
console.log(score ?? defaultScore); // ✅ 0 - preserved!
That’s because 0 is not null or undefined, so ?? keeps it.
Why ?? Is a Safer Bet
- Preserves valid falsy values like
0,false, and"" - Avoids accidental overwrites with defaults
- Helps make your code more predictable and readable
If you’re writing form logic, config defaults, or handling optional parameters — ?? is your new best friend.
Bonus Tip: Don’t Mix ?? and || Without Parentheses
// This throws an error!
const result = null || undefined ?? 'default';
Wrap expressions if you’re mixing them:
const result = (null || undefined) ?? 'default';
Found this useful? Share it with your dev team or bookmark it for your next project.
A message from our Founder
Hey, Sunil here. I wanted to take a moment to thank you for reading until the end and for being a part of this community.
Did you know that our team run these publications as a volunteer effort to over 200k supporters? We do not get paid by Medium!
If you want to show some love, please take a moment to follow me on LinkedIn, TikTok and Instagram. And before you go, don’t forget to clap and follow the writer️!
메타데이터
- post_id
- a76902b91a09
- slug
- mastering-default-values-in-javascript-with-the-operator-a76902b91a09
- url
- https://javascript.plainenglish.io/mastering-default-values-in-javascript-with-the-operator-a76902b91a09
- canonical_url
- https://javascript.plainenglish.io/mastering-default-values-in-javascript-with-the-operator-a76902b91a09
- author_url
- https://medium.com/@gatikrajput08
- status
- ok
- fetched_at
- 2026-07-22 06:37:29