Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Quickstart Arrays and Loops Write a Loop with for...of

Jenny Le
Jenny Le
4,883 Points

Is that always compulsory for passing it to the console?

array1.forEach(function(element) { console.log(element); });

4 Answers

If you want to log every item to the console separately, you can either use the forEach() method or a for loop.

The forEach() method runs the function once for each array element, by passing it the respective array[i].

Hence, the argument “element” refers to the current element being processed in the array.

Let’s say:

let array1 = [1, 2, 3];

array1.forEach(function(element) {       
     console.log(element); 
});

When you run your code, it will take each element once and run the provided function, logging it to the console.

Your expected output would be:

// expected output: “1”
// expected output: “2”
// expected output: “3”

Alternatively, you could use a for loop to iterate through the array:

let array1 = [1, 2, 3];

for ( let i = 0; i < array1.length; i++ ) {
     console.log(array1[i]); 
};

I hope this helps!

Jenny Le
Jenny Le
4,883 Points

Thank you so much! although it's not really the information that i was seeking but this definitely helps me in the future! :D

Jenny Le, sorry, I guess I didn't catch what you were aiming at with the question. :) What exactly did you mean?

Jenny Le
Jenny Le
4,883 Points

Oh, actually i have to say sorry cause my question was not clear. I meant i was solving the ForEach loop challenge and i was not sure if i also had to log items to the console or not! But your information was definitely useful! Thank you so much!