Array Iteration
Objectives
- Use a for loop to iterate over an array
- Use forEach to iterate over an array
- Compare and contrast for loops and forEach
var colors = ["red", "orange", "yellow", "green"];
for(var i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
For Loop
To loop over an array using a for loop, we need to make use of the array's length property
var colors = ["red", "orange","yellow", "green"];
colors.forEach(function(color){
//color is a placeholder, call it whatever you want
console.log(color);
});
ForEach
JavaScript provides an easy built-in way of iterating over an array: ForEach
arr.forEach(someFunction)
//using forEach
var colors = ["red", "orange","yellow", "green"];
colors.forEach(function(color){
console.log(color);
});
For vs. ForEach
The following 2 code snippets do the same thing:
//with a for loop
var colors = ["red", "orange", "yellow", "green"];
for(var i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
var numbers = [1,2,3,4,5,6,7,8,9,10];
var colors = ["red", "orange", "yellow", "green"];
numbers.forEach(function(color){
if(color% 3 === 0) {
console.log(color);
}
});
Exercise
What does the following code print out?
Array Iteration
By Colt Steele
Array Iteration
- 18,946