Normye
Normye

Reputation: 27

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

Upvotes: 1

Views: 65

Answers (2)

Carsten Massmann
Carsten Massmann

Reputation: 28196

Here is an alternative way, using Array.prototype.reduce():

function findLargestElement(txt) {
  return txt.split(/\W+/)//.reduce((a,c)=>a.length>c.length?a:c);
}
console.log(findLargestElement('My name is Carsten and I like JavaScript - much more than Java.')) // JavaScript 

Upvotes: 0

Adnan Malik
Adnan Malik

Reputation: 81

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

Upvotes: 2

Related Questions