The JavaScript Array iteration methods operate on all the elements of an array.
The following examples compare the iteration methods, that take a function as an argument, to for
loops, where the code that is applied to each element is in the body of the for
loop.
The examples use the arrow syntax.
Single parameter
function
Syntaxname => { console.info(name); }
name => console.info(name)
Multiple parameters
function (name) {
console.info(name);
}
(name, i) => { console.info(i, ':', name); }
(name, i) => console.info(i, ':', name)
function (name, i) {
console.info(i, ':', name);
}
These examples assume the following definitions. dayNames
is an Array of the names (Strings) of the days of the week. stringLength
is a function that returns the length of a string.
const dayNames = [
"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
function stringLength(str) {
return str.length;
}
for
loopsarray.forEach
What it does: Do something (call a function for its effect) to each item in an array. Ignore the result.
dayNames.forEach(name => console.info(name));
for (let i = 0; i < dayNames.length; i++) {
console.info(dayNames[i]);
}
Both of the snippets above print the following to the JavaScript console:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
A variant uses the array index:
dayNames.forEach((name, i) =>
console.info('Day #' + (i + 1) + ' is ' + name));
for (let i = 0; i < dayNames.length; i++) {
console.info('Day #' + (i + 1) + ' is ' + dayNames[i]);
}
These snippets print the following:
1. Monday
2. Tuesday
3. Wednesday
4. Thursday
5. Friday
6. Saturday
7. Sunday