JavaScript Task - Find longest Word in String

Hello fellow Campers,

I am working on the fifth task of the Basic Algorithm Scripting - Chapter and cannot seem to figure out why I keep getting an error.

This is my solution which produces the following error “TypeError: Cannot read property ‘length’ of undefined.”

What is it that I miss?

function findLongestWord(str) {

var array = [];
var stringcontainer = ‘’;
var stringbuffer = ‘’;
var arraylen = 0;

array = str.split(’ '); // splitting string into an array

arraylen = array.length; // determining length of array

//comparing each array element to find longest one
for (var a=0; a<=arraylen; a++){
stringbuffer = array[a];
if (stringcontainer.length < stringbuffer.length)
stringcontainer = array[a];
}

return stringcontainer.length;
}

findLongestWord(“The quick brown fox jumped over the lazy dog”);

1 Like

make sure your quotation marks are in pairs… ie; ("")

1 Like

While looping through here, it’s working fine for values of a from 0, 1, 2 etc until you hit a=arraylen…
At that point stringbuffer will be undefined, and that causes the error when it tries to evaluate stringbuffer.length.
You’ll want to use for (var a=0; **a<arraylen**;a++) or otherwise fix the loop so that it stops when there are no more words to look at.

1 Like

You were right, Yuzu-r! I hat to remove the <= from my for loop and replaced it with < . Now it works perfectly. Thank you for your help!

1 Like

You can try this answer:


<redacted>

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

If you want to compare your solution to others, use the Get a hint button on the challenge and there are alternative solutions you can compare yours to. Also, you can probably search older posts using the forum search feature or google the challenge name and find more there.

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

Thank you for understanding.

1 Like