var map = {}; map[key] = value;
How can I
Could I do better than:
if (map[key] == null) map[key] = 0; map[key] = map[key]++;
JavaScript has an even more succinct syntax to increment a number by 1. The increment operator ( ++ ) increments its operand by 1 ; that is, it adds 1 to the existing value. There's a corresponding decrement operator ( -- ) that decrements a variable's value by 1 . That is, it subtracts 1 from the value.
The value i++ is the value of i before the increment. The value of ++i is the value of i after the increment. Example: var i = 42; alert(i++); // shows 42 alert(i); // shows 43 i = 42; alert(++i); // shows 43 alert(i); // shows 43. The i-- and --i operators works the same way.
Description. If used postfix, with operator after operand (for example, x++ ), the increment operator increments and returns the value before incrementing. If used prefix, with operator before operand (for example, ++x ), the increment operator increments and returns the value after incrementing.
If we use the "++" operator as a prefix like ++varOne; , the value of varOne is incremented by one before the value of varOne is returned. If we use ++ operator as postfix like varOne++; , the original value of varOne is returned before varOne is incremented by one.
Here you go minimize your code.
map[key] = (map[key]+1) || 1 ;
Recently it could be
map[key] = (map[key] ?? 0) + 1;
Nullish coalescing operator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With