Find the Longest Word in a String - Order of Operations

I have settled on this solution, and while I understand the individual components and how it works, I don’t quite understand the order of operations.

function findLongestWordLength(str) {
  return Math.max(...str.split(" ").map(i => i.length));

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

Which part of this function executes first?

1 Like

Parentheses have the highest precedence, so everything inside Math.max() is evaluated first. Here’s the order -

  1. str.split(" ") - is the first to be executed. Results in an array of space-separated strings from str.
  2. map(i => i.length) - executes next on the array of strings, each string is mapped to its corresponding length, and a new array is returned.
  3. The spread operator is used on the array returned from step 2, and the resulting arguments are passed into Math.max(), which returns the largest number.
1 Like

here is the detail code to understand :

function findLongestWordLength(str) {
  // making an array of string
  var arr = str.split(" ");
  //map through the arr and getting the length of eachItem
  var itemLength =>eachItem.length) 
  // this will return 
  //  [ 3, 5, 5, 3, 6, 4, 3, 4, 3 ]
  // now the last part 

  return  Math.max(...itemLength);
  findLongestWordLength("The quick brown fox jumped over the lazy dog"))

Hope you got the point. split - map - max

1 Like

Thank you @thetradecoder and @Manish-Giri - this helped so much!

1 Like