How might I add check to see if a key already exists, and if does, increment the value, and if it doesn\'t exist, then set the initial value?
Something like this pseudo-
@snak's way is pretty clean and the ||
operator makes it obvious in terms of readability, so that's good.
For completeness and trivia there's this bitwise way that's pretty slick too:
dict[key] = ~~dict[key] + 1;
This works because ~~
will turn many non-number things into 0
after coercing to Number. I know that's not a very complete explanation, but here are the outputs you can expect for some different scenarios:
~~(null)
0
~~(undefined)
0
~~(7)
7
~~({})
0
~~("15")
15