Why in this code
function findLongestWordLength(str) {
return Math.max(...str.split(" ").map(word => word.length));
}
Do we need the spread operator (…)
Why in this code
function findLongestWordLength(str) {
return Math.max(...str.split(" ").map(word => word.length));
}
Do we need the spread operator (…)
if you don’t use the spread opeartor, then the argument of Math.max would be an array, and Math.max doesn’t work with an array as argument
we can try to see what happens without:
the result is NaN
because Math.max accepts only numbers as arguments, not an array
the spread operator is needed to pass the numbers to the Math.max method one by one
str.split(" ") will give you array of words in your sentence.
In the next step,in map you are iterating over the array of words and returning a new array with length of each word.
Now max method doesn’t takes an array as an input,instead takes numbers separated by comma.So,to convert the array of word length into numbers,spread operator is required.