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

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]){
  return lengths[-1];

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

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.

Ah, I understand now. Thanks!