Search code examples
arraysfor-loopreturnconsole.log

Is there a way to console.log an array using a function containing a for loop?


I'd like to print an array using a function that contains a simple for loop. So far my code will only list the first item in the array. It seems the return value only allows for the function to run once. But how do I get the code to continue iterating over the loop until the ending condition is met?

function aureliaStuff() {
    let aureliaInventory = ["Red Leather Duster Jacket", " 10mm 
    Pistol", " Black Sunglasses", " A Harley Davidson Motorbike", " A 
    Pack of Camel Cigarettes", " A Sister of Mercy CD", " The Lost 
    Boys On VHS."];

        for (let i = 0; i < aureliaInventory.length; i++) {
            let item = aureliaInventory[i]

            return item;
        };
}

console.log(aureliaStuff());

It just prints the first item in the array, "Red Leather Duster Jacket" and nothing else.

Why can't I seem to log the full array when I return a variable from my loop?


Solution

  • function aureliaStuff()
    {
        let aureliaInventory = ["Red Leather Duster Jacket", " 10mm
                                Pistol", " Black Sunglasses", " A Harley 
                                Davidson Motorbike", " A
                                Pack of Camel Cigarettes", " A Sister of Mercy 
                                CD", " The Lost Boys On VHS."];
    for (let i = 0; i < aureliaInventory.length; i++) 
      {
        console.log(aureliaInventory[i]);
      }
    }
    
    aureliaStuff();