Search code examples
javascriptarraysfor-looptypeerrorvariable-length

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


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 an error

Thanks in advance


Solution

  • 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