I’m working on exercise 11, and frankly I’m just not getting it. The subject is callbacks.
I was able to write the following code, it works, and I understand how it works:
let calc = (x,y,cb) => cb(x,y)
let add = (x,y) => x+y;
let mult = (x,y)=>x*y;
let sub = (x,y)=>x-y;
let div = (x,y)=>x/y;
console.log(calc(5,8,add));
So I’m not completely lost.
Here is the code I’m struggling with as provided in the lesson:
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.`);
}
// notice how I use a function here as the parameter cb?
fancyPet('Zed', 44, 'Mr. Scruffles', 10, (name, age) => {
console.log(`Ooooh fancy ${name} you are ${age} old.`);
});
I understand most of this, except for how it knows that name=Zed and age=44. Its not referenced anywhere else. Its clearly right, because it works.
I was able to restructure it this way, but I can’t convince myself that this is truly a callback:
let petInfo = (owner_name, owner_age, pet_name, pet_age) => {
console.log(`Your name is ${owner_name}, your age is ${owner_age}, Your pets name is ${pet_name}, and your pets age is ${pet_age}`);
}
console.log(petInfo("Jason",37,"Fezzik",4));
This is a bit different than my calculator above because my console.log
was only in one place - outside all functions. In my restructured code the console that is actually executing is from within the function. So I’m passing the correct data in, but if this is truly a callback its not clear to me why I have to use a console log to pass this data.
Thanks for any help you can provide.
Edit: sorry for all the edits. Not too familiar with markdown and took a few tries to make the post look like it needed to