As I’ve been stuck for way too long in the Mini Linter project, I’ve decided to trace back my steps and make sure that I’ve learnt everything that I should to face this particular practice.
In that journey, I was trying to compare loops and iterators to be able to finally understand the true nature of 'em both, and I’ve come with what is next. It’s kinda silly, I reckon, but it’s made me understand the nature of the forEach iterator (with I was kinda of struggling with beyond logging a bunch of sentences with the elements of an array).
Basically, all I’ve done is applying the forEach iterator to the “compare friends in social media” exercise. The result is as follows.
First, with the nested loops:
// Nested loops vs forEach iterator
// Nested loop
let nathaliaFriends = ['Ernest','Jack','Peter','Miley','Sally','Xavier'];
let johnFriends = ['Jesus','Ernest', 'Joe','Peter','James','Monica'];
let commonFriends = [];
function compareFriends (nathaliaFriends, johnFriends) {
for (let i = 0; i < nathaliaFriends.length; i++) {
for (let j = 0; j < johnFriends.length; j++) {
if (nathaliaFriends[i] === johnFriends[j]) {
commonFriends.push(nathaliaFriends[i]);
}
}
}
return commonFriends;
}
console.log(compareFriends(nathaliaFriends, johnFriends));
And then, with the forEach iterator:
// forEach iterator
let nathaliaPals = ['Ernest','Jack','Peter','Miley','Sally','Xavier'];
let johnPals = ['Jesus','Ernest', 'Joe','Peter','James','Monica'];
let commonPals = [];
nathaliaPals.forEach(pal => {
if (johnPals.includes(pal)) {
return commonPals.push(pal);
}
});
console.log(commonPals);
The result seems to be the same, but I love to shorten code.
Now, my questions would be:
1.- As the result is the same, is the logic behind nested loops and the forEach iterator vastly differently? Or are the scenarios in which to use either one of them vastly different?
2.- .forEach is an iterator and .includes a method, right?
Thanks!
Cheers!