Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to idiomatically initialize to zero or increment a property?

Tags:

javascript

I love those short js oneliners. I'd like to know if there's something logical and elegant for:

  • intializing a variable to zero if undefined
  • increment by one otherwise.

Shorter than this preferrably ;)

var obj = {} ;   //some iterative called function obj.prop = obj.prop===undefined?0:obj.prop++; 
like image 253
Geert-Jan Avatar asked Nov 08 '12 21:11

Geert-Jan


People also ask

How do you increment the value of a object?

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 .

How do you increment a number in JavaScript?

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.

What is the meaning of i ++ in JavaScript?

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.

What is Incrementation JavaScript?

The increment operator ( ++ ) increments (adds one to) its operand and returns a value.


1 Answers

This will result in NaN for the first increment, which will default to 0.

obj.prop = ++obj.prop || 0; 
like image 147
I Hate Lazy Avatar answered Sep 22 '22 06:09

I Hate Lazy