For loop breaks too early

Tell us what’s happening:
Describe your issue in detail here.

can someone tell me why my forloop breaks at the first if test that returns true?

  **Your code so far**

function findLongestWordLength(str) {
let newstr =str.split(' ');
let word=newstr[0].length;
console.log(newstr.length)

for (let i = 0; i < newstr.length; i++){
if (newstr[i].length>word)
  word=newstr[i];
  console.log(word)

}
return word;
}

findLongestWordLength("The quick brown fox jumped over the lazy dog");
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36

Challenge: Find the Longest Word in a String

Link to the challenge:

What are you setting word to, when the it clause is met? Not asking what you intend it to be set to… What are you setting it to?

i actually got it to pass when i changed it to the length of the word in the array. but im just curious why is it when i set word to the word at the index of i , the for loop stops there?

Not so much that it stops, but comparing a number to an alphabetic string will have unexpected results.

First time through word gets set to “The”. Next time through, you’re comparing 5 (the length of “quick”) to "The". The comparison coerces 7 to "7" (number to string), and compares “7” to “The”.

Alphabetically, “The” is greater.

oh got it. now i see on the next iteration since word got modiefied to a string instead of a number. the next iteration compared a number to a string, which is not good. that explains why when i did this :

word=newstr[i].length;

it made things ok. because its back to comparing a number to a number again.
which is ok because all it wanted was to return the length not the string connected to it
.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.