Iterating Over Arrays

A common thing to do with arrays is to iterate over each of the values of an array individually. There are two ways to do so: 1. A for() loop.

var emp = ['Joe King', 'Amanda Huggenkiss', 'Justin Thyme'];
for (var i = 0; i < emp.length; i++) {
  console.log(emp[i]);
}

Output:

Joe King
Amanda Huggenkiss
Justin Thyme
  1. A forEach() loop.

    var emps = ['Joe King', 'Amanda Huggenkiss', 'Justin Thyme'];
    emps.forEach(function(emp) {
     console.log(emp);
    });

    We can simplify the code above using an arrow function!

    var emps = ['Joe King', 'Amanda Huggenkiss', 'Justin Thyme'];
    emps.forEach(emp => console.log(emp));

    Our output is the same for all three actually.

Now that you're comfortable with the basics of arrays, we'll move on to array methods.

Last updated