Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the spread operator needed for Math.max()?

function findLongestWordLength(str) {
let arr = str.split(' '); 
let lengths = arr.map(word => word.length);

console.log(Math.max(lengths));
}

findLongestWordLength("The quick brown fox jumped over the lazy dog");

console.log(Math.max(lengths)) results in NaN, console.log(Math.Max(...lengths)) works. Why does lengths need to be spreaded? Math.Max takes an array as its argument, & lengths is an array? Thanks

like image 808
Denby101 Avatar asked Jun 03 '26 19:06

Denby101


2 Answers

Math.max does not take an array. It takes a set of parameters. The spread operator provides all of the values of the array as individual parameters.

Math.max(...lengths)

is actually represented at runtime as:

Math.max(lengths[0], lengths[1], etc, lengths[n])
like image 170
TheJim01 Avatar answered Jun 06 '26 08:06

TheJim01


Math.Max takes an array as its argument

This is not the case according to MDN:

The Math.max() function returns the largest of the zero or more numbers given as input parameters, or NaN if any parameter isn't a number and can't be converted into one.

like image 25
coreyward Avatar answered Jun 06 '26 08:06

coreyward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!