Recently I was answering questions from Mike, and we got into callback functions.
He had some code like this:
for(let i=0;i < array.length; i++) {
//do something
}
This lead me to dive into Array.map and Array.forEach. The point of bringing those up, was to explain that you don’t normally have to write a raw “for” loop. Usually you will be iterating over an array, and you are able to utilize these helper methods to do this much faster.
array.forEach(item => console.log(item))
This single line of code took a lot of explaining. I try really hard to break out everything into variables when discussing new paradigms to new developers. The line above became:
let array = [1,2,3]
function forEachItem(item) {
console.log(item)
}
array.forEach(
forEachItem
)
Discussing how parentheses “call” or “invoke” functions was very helpful to Mike.
It’s a hard to comprehend passing a function as a variable, to another function.
In this case, we are passing the function forEachItem to the array.forEach function.
I tried to explain in multiple ways that you are able to write code yourself that invokes functions passed in.
Fundamentally this concept is no different than passing in a number or a string, yet it takes a lot longer for most of us to comprehend.
Do you have any tips or tricks for understanding callback functions? Please let us know!
The key idea that seemed to stick was the parentheses conversation. If we pass a function without using parentheses to invoke it, then the consuming function is able to invoke it whenever it wants to.
By showing before and after of a raw for loop, then the .forEach method…. and then building our own forEach function that mimics the built in array method, I believe Mike was able to grasp the concept.
In the end, you’ll only fully understand it after using it many times in addition to comprehending it at a basic level.
Soon we will get into promises, and I’ll be able to explain how you can use those to negate the need and pointless nesting that callbacks can cause!