Newbie JS Question: Can I pass an array as an argument?

weirdichi

Diamond Member
Sep 19, 2001
4,711
2
76
Code:
var array1 = ["1", "22", "333", "4444", "55555"];
var currentLongWord = 0;

function longestWord(arrayName) {

    for (var i=0; i<arrayName.length-1; i++) {
        if (arrayName[i].length>currentLongWord) {
             currentLongWord = arrayName[i].length;
        }
    }
}

console.log(longestWord(array1));
The goal is to cycle through the array and print the number of characters from the longest element. When I run it, it returns an undefined. I've googled this and still find no answers. What am I doing wrong here?
 

Cogman

Lifer
Sep 19, 2000
10,283
134
106
yup. you are missing a return statement.

Also, currentLongWord should NOT be in the global scope. Move it into the function (globals are slower than locals in javascript and they make code harder to maintain).
 

Leros

Lifer
Jul 11, 2004
21,867
7
81
What the above said, plus you have a bug:

Code:
 for (var i=0; i<arrayName.length-1; i++)
should be
Code:
 for (var i=0; i<arrayName.length; i++)

It will only enter the loop when i < arrayname.length. Thus, when i = arrayName.length, it will exit the loop. The last iteration of the loop will be with i = arrayName.length - 1, which is the last element in your array.