JavaScript Callbacks with Harry Potter

What are they?

Callbacks aka higher-order functions, are functions that are passed into another function. These passed in functions are then executed inside that first function. Callbacks are especially helpful when you want to group related things together and perform the same action on all of them at once. Callback functions are also closures because they are executed at some point inside the main function’s body.

How do they work?

When a callback function is passed as an argument in another function, only the function’s definition is getting passed through. It is not executing the function. Since the containing function has the callback function in its parameter as a function definition, it can execute the callback anytime.

Guidelines on callback and why we use them:

  • Use named OR anonymous functions as callbacks
  • Pass Parameters to callback functions
  • Make sure the callback is a function before executing it
  • Multiple callback functions are allowed
  • Readable and DRY (don’t repeat yourself) code
  • Have more specialized functions or generic functions that are versatile

Example:

It’s the start of year 4 at Hogwarts, and Hermione wants to keep a daily log to keep track of her progress so that she can maximize her preparation for the O.W.L’s next year.

Because Hermione is extremely efficient and super smart, she quickly realizes a pattern in her days and comes up with a solution so that she doesn’t have to continually log the same things over and over again.

So now her daily logs are neat and tidy, and she only has to add things that are unique to her day.

Now she can check what she did on Monday, or any other day to better prepare for the following week.

While this saved her so much time, Hermione is a perfectionist and wants to make things a little more efficient. Not that she would ever forget, but Hermione wants to be able to see what days she sets aside for certain tasks. For example, on Mondays and Wednesdays she always studies at the library. Using Inline Functions, she can set a reminder to see what her days would look like.

So now when she calls postSchool, she will see that Library days are Mondays and Wednesdays.

Hermione is now ready to conquer those O.W.L’s

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.