Search code examples
javascriptternaryoperands

Javascript ternary operator hidden logic


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?


Solution

  • 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, ...