06 Iterables & Loops - Gilian/001-ES6-By-Wes GitHub Wiki
Iterables & Loops
First some already established for-loops and in the end the new of-loop with some examples.
The old loops and the disadvantage
// Array for all example codes
const cuts = ['Chuck', 'Brisket', 'Shank', 'Short Rib'];
// Ugly syntax
for (let i = 0; i < cuts.length; i++) {
console.log(cuts[i]);
}
// No way to break out of the loop
cuts.forEach((cut) => {
console.log(cut);
if(cut === 'Brisket') {
continue;
}
});
// Displays alternations to the prototype (added functions i.e.)
for (const index in cuts) {
console.log(cuts[index]);
}
The for-of-loop
The for-of-loop is nearly always usable, except for iterating objects:
for (const cut of cuts) {
if(cut === 'Brisket') {
continue;
}
console.log(cut);
}
// Gives value and index and gets instantly destructured
// .entries() is ES7, you could use the in-loop instead
for (const [i, cut] of cuts.entries()) {
console.log(`${cut} is the ${i + 1} item`);
}
// If you don't now the number of arguments comming in
function addUpNumbers() {
let total = 0;
for (const num of arguments) {
total += num;
}
console.log(total);
return total;
}
addUpNumbers(10,23,52,34,12,13,123);
Iterate an object
// Object
const apple = {
color: 'Red',
size: 'Medium',
weight: 50,
sugar: 10
};
for (const prop in apple) {
const value = apple[prop];
console.log(value, prop);
}
// not ready yet? (ES7)
for (const propp of apple.entries()) {
console.log(propp);
}