P Clinkscales P Clinkscales - 1 year ago 62
Javascript Question

How does this code know to return the length of the longest word in the string?

This is my code:

function findLongestWord(str) {
var arr = str.split(" ");
var p = 0;
for (i = 0; i < arr.length; i++) {
if (arr[i].length > p){
p = arr[i].length;
return p;

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

I know it works, but I am unsure why it is able to pick out only the longest word of the string. I understand that the sting gets split into an array, and the for loop checks the length of each string in the array, but how does
ALWAYS pick the longest one to return?

Answer Source

At the begin p is equal to 0

for (i = 0; i < arr.length; i++) { //loop all words in array

if (arr[i].length > p){

only if p (the length of previous word) is longer than current

p = arr[i].length; //I update p with the current length (not always, but according to if statement)

So at end of loop p is equal to the length of longest word.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download