Home > OS >  Why do I get "TypeError: Cannot read property 'length' of undefined" when using
Why do I get "TypeError: Cannot read property 'length' of undefined" when using

Time:09-11

I wrote a function that returns the longest word

const longestWord = (phrase) => {

const arr = phrase.split(" ");
let longest;

for (let i = 0; i < arr.length; i  ) {

    if (arr[i].length > arr[i 1].length){
        longest = arr[i 1]
        [arr[i]] = [arr[i 1]]
    }
}
return longest;
}

let longWhich = longestWord("Web Development Tutorial");

console.log(longWhich);

But I get the following error:

    if (arr[i].length > arr[i 1].length){
                                 ^

TypeError: Cannot read property 'length' of undefined

Thanks in advance

CodePudding user response:

Problem is one i points to last element then i 1 is undefined there are multiple ways to doing this problem is scan the largest string in array one way is following

function findLargestElement(phrase) {
   const arr = phrase.split(" ");
    let max, len = arr.length, i=0;
        max = i
        // here scan the largest element of array
        for (let j = i   1; j < len; j  ) {
            if (arr[max].length < arr[j].length) {
                max = j
            }
        }
        return arr[max]
}
console.log(findLargestElement('i am adnan'))//adnan
  • Related