I'm trying to understand callbacks thoroughly and this is the fundamental missing piece. I've scoured the internet for this answer but most just talk about async callbacks.
Q 1: Why do some built-in methods like
Array.prototype.forEach()usesynchronous callbacks? What advantage does this feature provide?
Q 2: How do we decide it's time to use a synchronous callback when implementing custom methods of our own?
Background:
javascript's for of loop functionally does the exact same thing as its forEach() counterpart when talking about arrays. They both loop from the front to the end of the array. So why do we need both?
Two obvious differences (in general) I see are:
continue and break keywords, forEach() does notforEach() DOES use a synchronous callback.I see the importance of points 1 and 2, but I don't get point 3
Q: What advantage does forEach() provide by taking a
synchronouscallback as its argument?
An answer other than "it allows us to apply a function to each element" or allows us to "abstract away the logic" would be really helpful unless the answers are actually really just this obvious and I'm overthinking this.
Hope my question is unambiguous and super clear
Callbacks aren't inherently synchronous or asynchronous. A callback is just a function that was given as an argument to another function.
When that callback gets called, is up to function and typically some other event precedes that. If that event is itself asynchronous, then the call is also asynchronous.
This is completely separate from forEach and a for. The reason both exists, is probably a combination of the following:
for(.. of ..) wasn't a thing for a long time, and for(.. in ..) has some surprising behavior related to prototypes. This led to many libraries implementing a functional (for)each, most notably jQuery.each, is because lots of folks got confused around how variables behaved in scope/closures and loops. Doing a functional version makes it much easier to not have closure variables overwritten for previous iterations.Especially the first two reasons made $.each popular, to a point where a native forEach was added to the language.
There's fewer reasons to use forEach today, because:
forEach doesn't work with await.let and const so variables overwriting after each iteration of the loop is no longer an issue.for(... of ..) does what people expects (no need for hasOwnProperty).forEachSome people still opt to using forEach if the above bullets aren't a concern. I don't fully understand that, but you can't really argue style.