1

I loop through an array like this:

_.each(user.groupings, function(grouping){
    conversions[i][grouping]++;
  })
}

Sometimes, conversions[i][grouping] is already set, sometimes it isn't. When it isn't, it won't be set to one, as desired, but rather NaN. I know I could do:

_.each(user.groupings, function(grouping){
   if(conversions[i][grouping]){
     conversions[i][grouping]++;
    }
    else{
       conversions[i][grouping] = 1
    }
  })
}

But is there a shorthand?

Chuck
  • 998
  • 8
  • 17
  • 30
Himmators
  • 13,568
  • 33
  • 122
  • 214

3 Answers3

1

Something like this:

_.each(user.groupings, function(grouping){
    conversions[i][grouping] = (conversions[i][grouping] || 0) + 1;
  })
}

This works something like the C# null coalescing operator:

Is there a "null coalescing" operator in JavaScript?

Community
  • 1
  • 1
Paddy
  • 32,511
  • 15
  • 77
  • 112
1

My preferred syntax would be:

conversions[i][grouping] = conversions[i][grouping] ? conversions[i][grouping] + 1 : 1;

I think that is more readable than the || options but I guess that's personal preference. If you're just after the least possible code this would work:

conversions[i][grouping] = ++conversions[i][grouping] || 1;
DoctorMick
  • 6,553
  • 25
  • 24
0

Have you tried something like

conversion[i][grouping] = (conversion[i][grouping] || 0) + 1;

This code:

(conversion[i][grouping] || 0)

...will result in the value from the array if it's "truthy," or 0 if the value from the array is "falsey" (because of the way JavaScript's || operator words). The falsey values are undefined, null, 0, NaN, "", and of course, false; the truthy values are everything else. So if conversion[i][grouping] may be undefined or null and you want it to end up being 1 after the increment, we use the || to turn that into 0 before adding 1 to it and assigning the result back to the entry.

T.J. Crowder
  • 959,406
  • 173
  • 1,780
  • 1,769
Kami
  • 18,699
  • 4
  • 47
  • 63