-4

Array with json how to convert isNaN to number zero so if you ahve array 1,2,3 and subtract 1,2 how to subtract 1-1 2-2 3- NaN NaN should be 0 for 3-0

// Create variables to append player's + or - score per hole
        var golfStroke = scores[y].strokes[q];
        var parStroke = pars[z];
        var scoreStroke = parStroke - golfStroke;
        // Create if statement to change undefined array values to number 0 for calculation
        var isNum = function () {
            if (isNaN(golfStroke)) {
            return 0;
        } else {
            return golfStroke;
        }
        if (isNaN(parStroke)) {
            return 0;
        } else {
            return parStroke;
        };
        }
        console.log("The over or minus par is: " + scoreStroke);

Thanks

raam86
  • 6,785
  • 2
  • 31
  • 46
user2910182
  • 31
  • 2
  • 13

3 Answers3

4

A simple shorthand way of using 0 if you have NaN is to use JavaScript's curiously-powerful || operator:

var x = somethingThatMayBeNaN || 0;

Since NaN is falsey, if somethingThatMayBeNaN is NaN (or 0 or any other falsey value), x will be set to 0. If somethingThatMayBeNaN is truthy, x will be set to somethingThatMayBeNaN. When you're dealing with a numeric calculation, usually the only falsey values that you may have are 0 or NaN.


"Falsey" and "truthy": The "falsey" values are 0, "", NaN, undefined, null, and of course, false. Everything is is "truthy".

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    it's a good trick to use, but always think of you reading your code in 6 months, and add a comment before such a line to say explicitly what you're doing – zmo Oct 23 '13 at 07:21
  • @zmo: For very common idioms like this one, I wouldn't think you needed to call it out specifically. (This is probably in the top 10 JavaScript idioms.) I **am** a great believer in thinking about the poor sod (possibly yourself!) who has to maintain your code in six months, though. :-) If you think that person will be unfamiliar with it, a comment is a good idea. – T.J. Crowder Oct 23 '13 at 07:23
3

This will check if the value is NaN and then it assigns 0 to it.

anyNan = isNaN(anyNan) ? 0 : anyNan;
Jayram
  • 18,820
  • 6
  • 51
  • 68
0

Assuming is golfStroke that could be NaN, for example:

var scoreStroke = parStroke - ~~golfStroke;

In that way any number would remains the same, and any "falsy" value – like NaN – would become 0.

ZER0
  • 24,846
  • 5
  • 51
  • 54