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?
functiongetKeys(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?