Why doesn’t JavaScript have a shorthand for adding values with null treated as zero?

0
16
Asked By CuriousCoder123 On

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

Answered By JustAndOnlyJavaScript On

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!

Answered By QuestionerQ On

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!

Answered By SyntaxSavant On

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.

Answered By CodeNinja99 On

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.

Answered By DevDissector On

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.