Home > Enterprise >  Which arithmetic operator can produce not NaN result when one of operands will be NaN?
Which arithmetic operator can produce not NaN result when one of operands will be NaN?

Time:01-22

Just for interest. We have that NaN is spreading along side calculation.

1   NaN => NaN

Is there any operator which will stop this spreading. I mean something like:

<operator> NaN => number

or

NaN <operator> <operand> => number

or

<operand> <operator> NaN => number

NaN => number

CodePudding user response:

Actually in Ecmascript definition of (**) operator for numbers. Has a special case when second operand is 0 or -0.

https://tc39.es/ecma262/multipage/ecmascript-data-types-and-values.html#sec-numeric-types-number-exponentiate

So actually:

console.log(NaN ** 0) // will log 1

CodePudding user response:

The Javascript has a built-in method that detect a NaN, but you will need check this "Possible number" for each operand.

let possibleNumber = "4f";

console.log(isNaN(Number(possibleNumber)));

possibleNumber = "44";

console.log(isNaN(Number(possibleNumber)));

Output:

true
false

You can do some function to check and return some number that you want

function checkIfIsNaN(number,numIfTrue,numIfFalse){
    if(isNaN(Number(number))){ return numIfTrue} else{return numIfFalse};
}

console.log(checkIfIsNaN("44",4,10));
  •  Tags:  
  • Related