Look at @io_io’s link to see a similar thread. This concept is actually only difficult if you keep thinking of calling a callback as special. If you think of it only as just like passing any other value to a function, then it’s easier.
So, what if you did this:
const fancyPet = (owner_name, owner_age, pet_name, pet_age, cb) => {
cb(owner_name, owner_age);
console.log(`That person owns ${pet_name} who is ${pet_age} years old.`);
}
const myCB = (name, age) => {
console.log(`Ooooh fancy ${name} you are ${age} old.`);
}
const my_name = 'Zed';
const my_age = 44;
fancyPet(my_name, my_age, 'Mr. Scruffles', 11, myCB);
Now when you see my_name you know (from just how a normal function call works), that my_name will become owner_name inside fancyPet
. Then you also know that my_age will become owner_age inside fancyPet
.
That means that myCB will just become cb inside fancyPet
. There is absolutely no difference just because it’s a function. JavaScript doesn’t care, it’s just a variable it passes. It just so happens that you can then call this cb
variable inside fancyPet
.
Alright, now all I did–which is what confuses beginners but is what makes this a useful challenge–is I got rid of my_name, my_age, and myCB and moved their values (the stuff on the right of the =
) right into the fancyPet
function call at the end. That. Is. All. If you can make a variable for it with let
or const
then you can just put that value right in the function call.
So the key is being able to “parse” (which means read the structure of) that final callback syntax in your code. You probably hit this part:
(name, age) => {
console.log(`Ooooh fancy ${name} you are ${age} old.`);
}
At the end of your version of the fancyPet
code and your brain fell apart. But what I do is I hit that and I go “Pause, function call, read that, put it in my head as a variable, now I see that this code is in its own function and gets passed to fancyPet, ok that’s cb.”
That means you can do this yourself by rewriting code like this the way I did in my rewrite above. If you hit some part of a giant function call like this, pull out the variables and set them with let or const to see what they are, then put them back. Pulling that anonymous callback (that’s the () => {} without being assigned to a variable name) out and giving it a name let’s you suddenly see what it is. Then you just have to get used to doing that in your head when your read this kind of code.