Denby101
Denby101

Reputation: 151

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

Upvotes: 2

Views: 2190

Answers (3)

BritishWerewolf
BritishWerewolf

Reputation: 3968

If you're coming here because you are getting this error. JavaScript console that shows the error "Maximum call stack size exceeded".

My original code was spreading an array to find the max.
My array was so large, that this was causing an error.

let myArray = [1, 2, 2, 4, 3];
let max = Math.max(...myArray);
// `max` returns 4

This can be mitigated by using a reduce instead.

let myArray = [1, 2, 2, 4, 3];
let max = myArray.reduce((max, cur) => Math.max(max, cur), Number.NEGATIVE_INFINITY);
// `max` returns 4

Upvotes: 1

TheJim01
TheJim01

Reputation: 8876

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])

Upvotes: 8

coreyward
coreyward

Reputation: 80090

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.

Upvotes: 2

Related Questions