[Solved] Why does JS return NaN if I compare to numbers and assign the result to a new variable? [closed]


The following code outputs 8 as expected, when Bought and Sold are arrays of numbers.

Bought = [1,2,3,4];
Sold = [2,4,6,8];

maxBought = Math.max(...Bought);
    console.log(typeof(maxBought));
// returns `number`

maxSold = Math.max(...Sold);
    console.log(typeof(maxSold));
// returns `number`

let max;

if(maxBought > maxSold) {
    max = maxBought;
} else {
    max = maxSold;
}

console.log(max)

[edit] on the other hand, if any element of Sold is NaN, then your output will be NaN. You should consider filtering out NaN out of Bought and Sold before processing them

Bought = Bought.filter(x => !isNaN(x));
Sold = Sold.filter(x => !isNaN(x));

10

solved Why does JS return NaN if I compare to numbers and assign the result to a new variable? [closed]