Creative web developer with an eye for design and communication. JavaScript and React enthusiast. Proud @h4ckademy alumni.
Also objects, but they can be traversed in similar ways, as we'll see
The for statement is very much imperative
They also make avoiding mutation easier
const getFruitNames = fruits => { const fruitNames = []; for (let i=0; i < fruits.length; i++) { const fruit = fruits[i]; fruitNames.push(fruit.name); } return fruitNames; };
const getFruitNames = fruits => {
const fruitNames = [];
for (let i=0; i < fruits.length; i++) {
const fruit = fruits[i];
fruitNames.push(fruit.name);
}
return fruitNames;
};
We call i auxiliary variable for a reason
What matters is not the plumbing, but the business logic it enables
Computing is for machines, not us
Not at all uncommon for even basic stuff
const getFruitNames = fruits => { return fruits.map(fruit => fruit.name); };
const getFruitNames = fruits => {
return fruits.map(fruit => fruit.name);
};
const getFruitNames = fruits =>
fruits.map(fruit => fruit.name);
The auxiliary variable i is gone and we also get the fruit element right away
It almost reads like English
Divide and conquer
This is harder to do with for loops, particularly with nested elements
Works for iterables, too