• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

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

weirdichi

Diamond Member
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?
 
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).
 
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.
 
Back
Top