This piece of javascript code find the longest word, but what is the explanation?

I don’t understand in depth.

function findLongestWordLength(str) {
  return Math.max(...str.split(" ").map(word => word.length));
}
1 Like

Hello let me help you with this step by step.

function findLongestWordLength(str){ // to return something }

So the function here takes str as an argument where str is the sentence you want to check its longest word.
Lets get into the return statement:

Math.max() returns the largest of the zero or more numbers given as input parameters. So within it we pass in the str and we do some operations to it to enable checking of the longest word.
The three dots you see are the spread operator, they are used to makes a copy of the passed string, the .split() method splits the string, in our case (…str) into an array according to the contents within the brackets, the above splits the sentence after every space i.e" " .

.map() iterates through the contents of an array calling a function for each element in an array. word here represents each element within the array , in our case the words in our sentence and calls a function to check the length of the word and stores an array of the length of each word.

Now math.max() compares each of these lengths and determines the largest one which it returns.
i hope i have helped, in the freecodecamp editor you can dissect those methods above and see how they work individually to get a grasp.

1 Like

Thank you so much @geraldombuthia :slight_smile:

1 Like
function splitter(str){
//console.log("spaced split returns: " + str.split(" ") )
 console.log("unspaced split returns:" + str.split(""))
// console.log("hyphened split returns:" + str.split("-")
}
splitter("Here i am a software developer");
1 Like

try out this code and see how split works…

1 Like

You are welcome, hope you understand.

1 Like