0

Why does this code "(number % 2)" work the same as this code "(number % 2 == 1)" even tho i didn't specify how much the remainder of the division should be?

var number = parseInt(prompt("even or odd number checker"));
if (number % 2) {
  alert("odd");
} else {
  alert("even");
}

var number = parseInt(prompt("even or odd number checker"));
if (number % 2 == 1) {
  alert("odd");
} else {
  alert("even");
}
  • 2
    Because any integer modulo 2 is equal to 0 or 1, the result of a modulo operation can't be `>=` to the modulo itself – Cid Nov 18 '21 at 21:32
  • 1
    Anything but `0` is truthy (except sheNaNagins). – zero298 Nov 18 '21 at 21:33
  • 1
    I answered a similar question here: https://stackoverflow.com/questions/69966139/safest-way-to-guard-against-missing-and-undefined-parameters/69966195#69966195 You're evaluating truthiness in your conditional which is why it continues. – luxdvie Nov 18 '21 at 21:35
  • 4
    Does this answer your question? [In javascript is -1 true or false?](https://stackoverflow.com/questions/34726070/in-javascript-is-1-true-or-false) particularly the quote about the spec saying: "All values are truthy unless they are defined as falsy (i.e., except for false, 0, "", null, undefined, and NaN)" – zero298 Nov 18 '21 at 21:40

0 Answers0