Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
22
rated 0 times [  28] [ 6]  / answers: 1 / hits: 17516  / 12 Years ago, thu, november 8, 2012, 12:00:00

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++;

More From » javascript

 Answers
1

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



obj.prop = ++obj.prop || 0;

[#82095] Wednesday, November 7, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
terrence

Total Points: 120
Total Questions: 115
Total Answers: 87

Location: England
Member since Fri, May 22, 2020
4 Years ago
terrence questions
Sat, Jun 5, 21, 00:00, 3 Years ago
Wed, Jun 17, 20, 00:00, 4 Years ago
;