0

Can someone please explain to me why this JS function does not return 0 ?

let letters = [ 3, 1, "c" ];

const easySolution = function(input){
    if(Math.max(...input) === NaN){
        return 0;
    }else{
        return Math.max(...input);
    }
}
console.log(easySolution(letters));
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN#testing_against_nan - unless 0 is the largest value in the input, it won't get returned from that function. – jonrsharpe Jun 03 '21 at 20:07
  • 2
    Does this answer your question? [How do you check that a number is NaN in JavaScript?](https://stackoverflow.com/questions/2652319/how-do-you-check-that-a-number-is-nan-in-javascript) – snwflk Jun 03 '21 at 20:07

1 Answers1

1

You could also make it simpler by using the ternary operator and an arrow function (both ES6 features):

const easySolution = (input) => {
   return Number.isNaN(Math.max(...input)) ? 0 : Math.max(...input)
}
micnic
  • 10,915
  • 5
  • 44
  • 55