How to increment an object property value if it exists, else set the initial value?

dict[key] = (dict[key] || 0) + 1;

@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

Your pseudo-code is almost identical to the actual code:

if (key in object) {
    object[key]++;
} else {
    object[key] = 1;
}

Although I usually write:

if (!(key in object)) {
    object[key] = 0;
}

object[key]++;

Tags:

Javascript