After learning JavaScript syntax and then started doing algorithm problems I hit common wall . I realized i lack deeper understanding of what loops do and it seems they don’t work the way i think they do. Does somebody have a good resource to help me learn? Thanks.
Maybe if you could talk through what you do and don’t understand about loops, we can help make sense of it.
1 Like
yeah… i wasn’t clear. So first thing i don’t understand is when should i use which loop. What is the difference between for of, forEach, and for loop?
for…of iterates over elements.
for(const thing of collection) {
// do something with thing
}
// is the same as
for(let i = 0; i < collection.length; i++) {
const thing = collection[i];
// do something with thing
}
As you can see, it’s sometimes much tidier. If you don’t care about thing
's position in collection
, you can use a for..of
to skip right to the value.
forEach is what you want when you’re going to pipe every element of an array through a function.
someArray.forEach(thing => doStuff(thing));
// is the same as
for(const thing of someArray) {
doStuff(thing);
}
// or
for (let i = 0; i < someArray.length; i++) {
doStuff(someArray[i]);
}
Once again, we have a shorthand for a specific use of looping.
I hope that helps.
1 Like