Reputation: 39437
I can understand why
10 % "test"
returns NaN
... because "test" is converted to a number first which gives NaN
and then any subsequent arithmetic operation involving NaN
results in NaN
too.
But why does
10 % "0"
return NaN
?
"0"
is usually converted to a number as 0
e.g. in 1 * "0"
.
If I try 10 / "0"
this gives Infinity
which also makes sense.
So... why does that expression 10 % "0"
return NaN
?! Any logic behind this?
Upvotes: 0
Views: 71
Reputation: 10979
10 % 0
also returns NaN
because you're asking what's the remainder when you divide by 0, and there's no meaningful answer to that.
Upvotes: 2
Reputation: 10384
Your guess is right, in all the number only operators, if used in strings, Javascript will try to convert them in numbers.
The same also happens with the remainder operator:
const x = "10"%"3";
console.log('10 % 3 = ' + x);
So why you get NaN
evaluating 10%"0"
? Well, it will be converted to 10%0
, but the remainder operator has no particualr meaning if used on 0 (you can't divide by 0 in first instance). So you get NaN:
const x = 10 % 0; // numeric only operation
console.log('10 % 0 = ' + x); // NaN, the above operation has no meaning
Upvotes: 4