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:
- for of loop can loop over any iterable, forEach is specific for arrays.
- for of loop allows us to use
continue
andbreak
keywords, forEach() does not - for of loop does NOT use a callback,
forEach()
DOES use asynchronous 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
synchronous
callback 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