0

When we have an object with a numeric property that works as an accumulation. What's the best way to deal the "accumulate/create" case in ES6 javascript? The simplest way would be:

if (obj.foo)) {
    obj.foo += value;
}
else {
    obj.foo = value;
}

or

obj.foo = obj.foo ? obj.foo + value : value;

ideas to improve this? thanks!

Colo Ghidini
  • 658
  • 9
  • 20
  • 2
    what about initializing the `foo` like `var obj = {foo:0}` always, then you don't need to worry about if `foo` exists? – Sphinx Mar 05 '18 at 21:52
  • 2
    @Sphinx That's good advice. The question would be more appropriate if the property were dynamic, so you can't pre-create all the properties. – Barmar Mar 05 '18 at 21:55
  • @Barmar yes, that's the case, in my case, it is a dynamic key for this new property – Colo Ghidini Mar 05 '18 at 21:57

2 Answers2

5

Check for the current value or initialize with 0 then add.

obj.foo = (obj.foo || 0) + value;
Ele
  • 33,468
  • 7
  • 37
  • 75
0

Since undefined + number => NaN and boolean coercion of NaN is false !!NaN === false then:

obj.foo + 1 can only be NaN or a number so you can simply do:

obj.foo = obj.foo + value || value; // if obj.foo + 1 is NaN, then the result is 1.

Despite the fact that this looks simple, bear in mind that due to implicit coercion 0 and NaN are both false: !!0 === !!NaN so this is only recommended for positive numbers other than 0.

In that case if obj.foo + value === 0 the function above will be 1 instead of 0.

Ignacio Bustos
  • 1,415
  • 2
  • 17
  • 26