-6

function even_or_odd(number) {
  return number % 2 === 0 ? 'Even' : 'Odd';
}

function even_or_odd(number) {
  return number % 2 ? "Odd" : "Even"
}
Why do these two functions return the same result?

How does return number % 2 ? "Odd" : "Even" work?

Elan
  • 539
  • 1
  • 6
  • 18

1 Answers1

1

0 in javascript is a falsy value.

var v = 0;

if(v) {
  console.log("true");
} else {
  console.log("false");
}

number % 2 will return either 0 (which is falsy) or 1 (which is truthy). So if the number is even then number % 2 will return 0 and the condition of the ternary will be false, ...

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73