Find the longest word in a string_Why does this code not work?

Find the longest word in a string_Why does this code not work?
0

#1

Hello. Could someone explain to me why the following code doesn’t work?

function findLongestWordLength(str) {
  let arr = str.split(' ');
  let lengths = [0];
  for (let i = 0; i <= arr.length-1; i++) {
    let counter = arr[i].length; 
    if (counter > lengths[-1]){
      lengths.push(counter);
    } 
  }
  return lengths[-1];
}

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

#2

Before your return statement, the lengths array looks like [0]. It has one element and the element is the number zero. Arrays are zero-indexed, meaning they start at 0 and go up through one less than the length of the array. When you refer to a negative index such as -1, there are no such elements at such an index, because that index does not exists, so the value of undefined is returned.

You have the same issue in your if statement where you try to compare counter with lengths[-1]. JavaScript is not like Ruby or Python where you can refer to negative indices and it will move back from the end of the array.


#3

Ah, I understand now. Thanks!