I love those short js oneliners. I'd like to know if there's something logical and elegant for:
Shorter than this preferrably ;)
var obj = {} ; //some iterative called function obj.prop = obj.prop===undefined?0:obj.prop++;
To increment a value in an object, assign the value of the key to the current value + 1, e.g. obj. num = obj. num +1 || 1 . If the property exists on the object, its value gets incremented by 1 , and if it doesn't - it gets initialized to 1 .
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.
The increment operator ( ++ ) increments (adds one to) its operand and returns a value.
This will result in NaN
for the first increment, which will default to 0
.
obj.prop = ++obj.prop || 0;
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