Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
124
rated 0 times [  127] [ 3]  / answers: 1 / hits: 12820  / 5 Years ago, mon, october 21, 2019, 12:00:00

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.


More From » typeerror

 Answers
10

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


[#5867] Thursday, October 17, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jarod

Total Points: 62
Total Questions: 111
Total Answers: 83

Location: Saint Vincent and the Grenadines
Member since Sat, Sep 11, 2021
3 Years ago
jarod questions
Sun, Aug 23, 20, 00:00, 4 Years ago
Sun, Apr 26, 20, 00:00, 4 Years ago
Wed, Dec 18, 19, 00:00, 5 Years ago
Sat, Sep 21, 19, 00:00, 5 Years ago
;