sourlemonaid sourlemonaid - 2 months ago 8
Javascript Question

setting the length of an array's string element to a variable in a for loop in javascript

I have this code. and for some reason i get the error:

Uncaught TypeError: Cannot read property 'length' of undefined
. I can't seem to figure out why.



function findShort(s) {

var c = s.split(' ');
var l = c[0].length;
var wordlength;

for (var i = 1; c.length; i++) {
console.log(c[i].length);

wordlength = c[i].length;
if (l < wordlength) {
l = wordlength;

}
}
return l;

}

console.log(findShort("hello dog cat 12 asdsad wuidhuiwqhd"));





the error is with the line
wordlength = c[i].length;


When i console.log it, it shows the length of each string in the array. However, when i try to store that length it says it's undefined.

Answer

You need to change this line

for ( var i = 1; c.length; i++ ) {

to

for ( var i = 1; i<c.length; i++ ) {

The second componenet of a for loop is a boolean condition that is checked for every round of the loop to determine if the loop should continue or not. By putting c.length, you are giving a constant value which will make the loop to either never run (if c.length is 0), or to run forever (if c.length not 0).

You should also be careful with the following line:

var l = c[0].length;

It might cause a problem too as it is not guaranteed that c will have at least one element.

Comments