DEV Community

w6
w6

Posted on • Edited on

How to get every item in an array for beginners.

Step 1: Create your array.

Create your array like this

  const MyArray = ["Item 1", "Item 2"];
Enter fullscreen mode Exit fullscreen mode

Step 2: Create the Method1 function

Add a function that looks like this

 function method1(arr) {
   for (var i = 0; i < arr.length; i++) {
     console.log("Method 1: " + arr[i]);
   }
  }
Enter fullscreen mode Exit fullscreen mode

And add this code to call the function:

  method1(MyArray);
Enter fullscreen mode Exit fullscreen mode

Now open the index.html file and look in the console. It should say something like this: looparray1
If it does you successfully looped over an array and console logged it!

Aditional Methods:

If you want something more simple but slower than the traditional for loop you can try out these functions:

function method2(arr) {
  for (const e of arr) {
    console.log("Method 2: " + e)
  }
}
function method3(arr) {
  arr.map(e => e).forEach(e => {
    console.log("Method 3: " + e);
  })
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading my first article!

Top comments (4)

Collapse
 
bakedbird profile image
Eleftherios Psitopoulos

Is there any specific reason you chained map and forEach on the third method that I am missing?

Collapse
 
w6 profile image
w6

No, each method chained together is another iteration over the array.

Collapse
 
bakedbird profile image
Eleftherios Psitopoulos

Yes, I’m just asking because I don’t think it’s really needed there, unless you’re planning to return the array.

Thread Thread
 
w6 profile image
w6

Thank you for the feedback!