Skip to content

Instantly share code, notes, and snippets.

@brainyfarm
Created June 21, 2016 14:06
Show Gist options
  • Save brainyfarm/410ac2faefdc9070b9017e19a25f6b4b to your computer and use it in GitHub Desktop.
Save brainyfarm/410ac2faefdc9070b9017e19a25f6b4b to your computer and use it in GitHub Desktop.
Olawale/FreeCodeCamp: Find Longest Word in a String
function findLongestWord(str) {
//Split each word into an array
var arrayString = str.split(" ");
// longest_so_far as declared before looping
var longest_so_far = 0;
// Let us loop to find the largest items
for (var i = 0; i < arrayString.length; i++) {
// Is the length of the current item greater than value of longest_so_far?
//If so, longest_so_far would now be the value of the length of the current item
if(arrayString[i].length > longest_so_far){ longest_so_far = arrayString[i].length;}
}// End of loop;
// Return longest_so_far's value which would be the length of the longest string
return longest_so_far;
}// End of function
// This could be done with less code using Maths.max() in combination with arr.map();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment