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
  • 14,278
  • 36
  • 132
  • 223

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
  • 33,309
  • 15
  • 79
  • 114
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,703
  • 28
  • 26
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
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Kami
  • 19,134
  • 4
  • 51
  • 63