Step 1: Create your array.
Create your array like this
const MyArray = ["Item 1", "Item 2"];
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]);
}
}
And add this code to call the function:
method1(MyArray);
Now open the index.html file and look in the console. It should say something like this:
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);
})
}
Thanks for reading my first article!
Top comments (4)
Is there any specific reason you chained map and forEach on the third method that I am missing?
No, each method chained together is another iteration over the array.
Yes, I’m just asking because I don’t think it’s really needed there, unless you’re planning to return the array.
Thank you for the feedback!