I'm curious why JavaScript hasn't introduced a shorthand operator that treats null as 0 when you use something like +=. It often leads to extra coding steps to ensure this behavior. For instance, I usually end up doing things like this:
const obj = {};
for (const item of list) {
if (!obj[item.id]) obj[item.id] = 0;
obj[item.id] += item.amount;
}
or with the nullish coalescing operator:
obj[item.id] = (obj[item.id] ?? 0) + item.amount;
Wouldn't it make more sense to have a shorthand option like obj[item.id] +== item.amount? Just looking for a bit of convenience here!
5 Answers
That's an interesting approach, but there are likely existing proposals that could address this without altering the language dramatically, such as the upsert proposal. It's worth checking out!
I see your point, but what if I want a different default value rather than zero for a missing key? A universal solution could be adding default value support in Maps, like a get method that allows specifying a default. This might improve both convenience and performance!
A null value often indicates a mistake in code rather than an acceptable operand. Developers have to be cautious with such cases, so keeping the default behavior as it is may help prevent bugs. Plus, the idea of making the += operator automatically treat null as zero could confuse less experienced developers and lead to unexpected results.
You can actually simplify this a bit with the nullish coalescing assignment operator (??=). Try this:
obj[item.id] ??= 0;
obj[item.id] += item.amount;
It doesn’t change the behavior of += but offers a clearer syntax.
Changing the behavior of the += operator to treat undefined or null as zero would be a backward-incompatible change. Right now, undefined + 5 gives NaN, and that’s a behavior that many existing codebases depend on. Using existing tools like ?? or ??= keeps things safer and more predictable.

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically