Having taken several Python courses in the past, I was a little confused by the JS for loop (I since understand how it works) because you iterate over the indices. The .forEach() method hits a little closer to home as it allows you to iterate over the actual values of an array.
In the Mozilla documentation I came across another for loop that reminds me of the Python for loop (and the for…in loop for objects:
const fruits = ['mango', 'papaya', 'pineapple', 'apple'];
for (let fruit of fruits) {
console.log(`I want to eat a ${fruit}`)
}
This will print the exact same result to the console as:
fruits.forEach(fruit => console.log(`I want to eat a ${fruit}`));
namely:
I want to eat a mango
I want to eat a papaya
I want to eat a pineapple
I want to eat a apple
Is there any preference or reason why to choose the forEach() method over the for…of loop?
forEach() gives a nice readable expression with no overt iteration. It also lets us access both value and index in one stroke. Empty elements are ignored.
It should be noted that we cannot break a forEach loop. Being as it is exclusively an Array method, we can expect some optimization, as well.
Because it is an iterator that takes a callback, we can write standalone functions that make for very readable code.
const toEat = x => console.log(`I want to eat ${x}.`);
fruits.forEach(toEat)
Hello there! I am having trouble with the first lesson.
The excersice says that we need to do the following:
Iterate over the fruits array to log I want to eat a plus the name of each fruit to the console. For example, I want to eat a mango .
You may use any form of callback you prefer.
I am using arrow function to write the code in less lines, it looks like this:
I want to eat mango
I want to eat papaya
I want to eat pineapple
I want to eat apple
But I am getting this error:
In your callback function do you console.log() to print 'I want to eat _____ ? In the blank, you should concatenate or interpolate the element in fruits array?
Is it because it is expecting of me to use a create a function that logs the elements in the array with the interpolated text and use it as a callback function in the .forEach()?
Update:
I already tried like this and I am still getting the same error:
That’s because the lesson was not about grammar and punctuation, but about the forEach() iterator. The instructions are clear about how the output text is composed, including the full stop that ends a sentence, as one would expect.