Why Doesn’t JavaScript Have a Short Hand for Null as Zero in Addition?

0
7
Asked By CuriousCat99 On

I've noticed that with all the new features being added to JavaScript, there still isn't a shorthand for adding values where null is treated as zero. It's a bit of a hassle to have to check for null or zero before doing the addition. For instance, I often find myself writing code like this:

```javascript
const obj = {};
for (const item of list) {
if (!obj[item.id]) obj[item.id] = 0;
obj[item.id] += item.amount;
}
```

Or using the nullish coalescing operator:

```javascript
const obj = {};
for (const item of list) {
obj[item.id] = (obj[item.id] ?? 0) + item.amount;
}
```

It would be much simpler if I could just write something like this:

```javascript
const obj = {};
for (const item of list) {
obj[item.id] +== item.amount;
}
```

2 Answers

Answered By TechWhiz123 On

It's usually better to treat null values as potential bugs rather than just defaults. PS: Using the nullish coalescing assignment operator can help: `obj[item.id] ??= 0; obj[item.id] += item.amount;`

Answered By CodeCrafter42 On

You could go with the nullish coalescing operator (??) which does almost what you're asking for. This keeps your code clearer and avoids potential confusion down the line. Like this: `obj[item.id] = (obj[item.id] ?? 0) + item.amount;`

DesignGuru88 -

Good point!

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.