Skip to content
JS Fundamentals: Objects, Arrays, and Functions
Share
Explore
Objects & Arrays

icon picker
Iteration

Iteration, looping — this is what we have to do to go through a data structure. You may be looking for a particular value, you may be moving data from one place into another data structure, making a copy, etc.
In JavaScript these days there are lots of ways to loop! Let’s start with the one most of us are probably familiar with. I call this the “regular” for-loop.
for (let i = 0; i < 5; i++) {
// Runs 5 times, with values of i 0 through 4.
console.log(i);
}
A bit of a fancier loop when working with arrays is the forEach loop:
const suspectNames = [
"Miss Scarlet",
"Col. Mustard",
"Mrs. White",
"Mr. Green",
"Mrs. Peacock",
"Prof. Plum"
];

suspectNames.forEach(suspectName => {
console.log(suspectName);
});
However it doesn’t really work with objects out of the box, but there is a little bit of a trick you can do:
const weapons = {
revolver: true,
knife: true,
leadPipe: true,
candlestick: true,
rope: true,
wrench: true
};

Object.keys(weapons).forEach(weapon => {
console.log(weapon);
});
How does Object.keys work?
function getKeys(obj) {
const result = [];

for (let prop in obj) {
if (hasOwnProperty.call(obj, prop)) {
result.push(prop);
}
}
return result;
}

console.log(getKeys({ 1: 1, 2: 3 }))
That’s a different loop. How is it different than the first for loop we discussed at the beginning?

Which loop is faster?

Check out the performance of these loops here:

Which loop should I use?

Are you planning to loop through the entire data set every time? forEach
Do you want to return an array? reduce
Do you want the array to be the same size as the input? map
Do you want the array to be the same or smaller as the input? filter
Do you want to look fancy? reduce
Are you planning to break or continue in you loop? regular loop
Are you planning to do something async in your loop? regular loop or maybe map
Is perf really important? regular loop

Next 👉


©2021 for

Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.