Late reply:
I just ran into a similar problem. I have an object that I want to hold counts of, well, no need to get into details of this app, let's just say I get a code and I want to count how many times each code occurs.
My first draft I initialized the object with all possible codes with value zero, like "let counts={F:0,C:0,M:0,N:0}. Then I had a loop with a switch on the code value. That seemed awkward, and required the counting function to know all possible codes.
My second draft I started to write
if (counts[code]==null) counts[code]=1
else counts[code]++
I presume that would have worked but it seemed inelegant. So I tried
counts[code]=+counts[code]+1
Didn't work. If counts[code] wasn't already defined, that returned NaN. It works if counts[code]==null, but not when counts[code] is undefined.
But this works:
counts[code]=(counts[code] || 0)+1
Not as elegant as I'd like but I generally prefer ugly code that works over pretty code that doesn't work. :-)
+ 0
will coerce anull
to a0
. – Cuesta