"Find The Longest String" - JavaScript vs Python strategy


I’m trying to solve the titular algorithm. Since I think in Python, I first did it using Python, which worked nicely:

def findLongestWord(string):
    cache = ""
    x = string.split(" ")

    for word in x:
        if len(cache) < len(word):
            cache = word

    return len(cache)

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

I found what were some equivalent expressions in JavaScript, and came up with the following:

function findLongestWord(str) {

  var cache = "";
  var x = str.split(" ");
  var word;

  for (word in x) {
    if (cache.length < word.length) {
      cache = word;

  return cache.length;

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

It didn’t work. It seems that the “for/in” loop in JS combined with .length in an array are counting the individual strings of the array as objects starting from 0 onward, not the individual characters of each string, thus ensuring “cache” will always return 0.

I know there are other solutions, and it can probably be solved in a line or two, but how can I solve this problem using a for/in loop…or, if that’s impossible here, at least using a similar strategy to my own?

Thank you.

Make it

for (let word of x) {


1 Like

Thanks, that was helpful.