JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Using For Loops with Arrays

why does this code not work?

    function printD(html) {
            return document.write(html);
    };


    var alphabetsZ = ["A", "B", "C"];


    function olArr(liArr) {
        var listz = "<ol>";
        for (var i = 0; i < liArr.length; i += 1) {
            listz += "<li>" + liArr[i] + "</li>";
        };
        listz += "</ol>";
    };

    printD( olArr( alphabetsZ ) );
// output -  undefined

i know the code is fine in general and if i put printD(listz); within the function and call the function as normal it will work fine. but trying a different way that i did, to me my way should work too. i know the problem is mainly :

    printD( olArr( alphabetsZ ) );

it comes off as undefined even though the code looks fine to me too! my guess is you cannot use function within a function?

1 Answer

Elijah Quesada
Elijah Quesada
Front End Web Development Techdegree Graduate 31,067 Points

You need to add a return statement. A function will return undefined by default. In order to return a value you need to add the return statement.

    function printD(html) {
            return document.write(html);
    };


    var alphabetsZ = ["A", "B", "C"];


    function olArr(liArr) {
        var listz = "<ol>";
        for (var i = 0; i < liArr.length; i += 1) {
            listz += "<li>" + liArr[i] + "</li>";
        };
      return  listz += "</ol>";
    };

    printD( olArr( alphabetsZ ) );

omg i feel so stupid that i forgot to add a return. thanks for the help Elijah