Caleb Mabry
Misadventures In Coding

Follow

Misadventures In Coding

Follow
JavaScript Callbacks

JavaScript Callbacks

Haven't had anyone call recently? Try and make your function callback instead!

Caleb Mabry's photo
Caleb Mabry
·Sep 14, 2022·

1 min read

You know how you can pass all sorts of things as arguments into a function?

function iEat(thing) {
  console.log("I eat " + thing);
}
iEat(5);
iEat("lots of things");
iEat(7.9840);
iEat(["pork", "beans"]);

NOW! Imagine we give a function a function as an argument!

iEat(thing, aFunction) {
  console.log("I eat " + thing);
  aFunction(thing);
}

Now, you can take the iEat(thing, aFunction) function, and make the second argument a function!

function myFunction(myFunctionArgument) {
  console.log("I am " + myFunctionArgument);
}

iEat(thing, aFunction) {
  console.log("I eat " + thing);
  aFunction(thing);
}

So, step by step:

iEat("Bananas", myFunction);
// ------------------------------
// You give iEat the word Bananas and the previous function
// we created, myFunction.
// Below, I'm going to put the individual arguments into 
// the function to try and make it easier to understand
//-------------------------------
iEat("Bananas", myFunction) {
  console.log("I eat " + "Bananas");
  myFunction(thing);
}

So when your function iEat makes a call to another function, aFunction this is considered a callback!

 
Share this