What Is a Callback in JavaScript

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 4 years ago

If you've used addEventListener, Array.filter, or many other methods in JavaScript, then you've already used a callback. Callbacks are often invoked inside of APIs of libraries where we don't get to see them called. This course explores internals and patterns where we have control of invoking the callback and discovering the features callbacks enable.

John Lindquist: [0:00] A callback is when you -- let's set up an addEventListener("andClick") -- it's when you pass a function like this function in as an argument. If I console.log(andClick), come over here and click a few times, this right here is a callback.

[0:18] If I cut this out and give it a name, we'll call it callback, solid ame, paste that right there, and then pass in my callback this still works. Click, click, click because this function is being called by the internals of this.

[0:36] If we don't use the document addEventListener and instead, we just make another function, and this function takes a function, and inside that function, we call that function three times.

[0:51] If I call another function with my callback, hit Save, you'll see click, click, click because this function is being passed in as an argument. That makes this function right here, which means that this function is being called one, two, three times.

[1:11] That's the power of a callback is that you can define a behavior and then pass that into another function, which controls when that function is called. I could call it three times. I could wrap within a statement. I could use for loops or any scenario you want to think of. I have complete control over when this callback is called.

egghead
egghead
~ 5 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today