Search code examples
javascripttypeerror

How to fix TypeError: Cannot read property 'length' of undefined in JavaScript?


I am trying to solve a very easy challenge about finding the longest word in a string. This is the code:

function find(par) {
    let arrayWord = par.split(" ");
    let longestWord = "";
    for (let i = 0; i <= arrayWord.length; i++) {
        if (longestWord.length < arrayWord[i].length) {
            longestWord = arrayWord[i]
        }
    }
    return longestWord;
}
find("Find the longest word");

I would need help understanding why I am getting this error:

Uncaught TypeError: Cannot read property 'length' of undefined at find (:5:47) at :11:1 find @ VM959:5 (anonymous) @ VM959:11

thank you.


Solution

  • Cannot read property 'length' of undefined comes when it is not able to find variable of certain type(In your case a string) to call the function length. In your case arrayWord[i].length is not a proper string for the last condition of your check as there is no element arrayWord[arrayWord.length] present in the array. That's why arrayWord[i].length is giving you an error for your last iteration. Just change i <= arrayWord.length to i < arrayWord.length

    function find(par) {
      let arrayWord = par.split(" ");
      let longestWord = "";
      for (let i = 0; i <arrayWord.length; i++) {
        if (longestWord.length < arrayWord[i].length) {
          longestWord = arrayWord[i]
        }
      }
      return longestWord;
    }
    

    Edits: Changes made as suggested by RobG