JavaScript Task - Find longest Word in String

JavaScript Task - Find longest Word in String
0

#1

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”);


#2

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


#3

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.


#4

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!