This is a Javascript function called sayHi. Whenever it is called/executed it will output the text “Hi!”.

function sayHi() {
  console.log("Hi!")
}

sayHi() // "Hi!"

We can also pass arguments to our function. For example, now our function has one parameter x. It will always output the content of whatever argument we pass in as a parameter.

function sayHi(x) {
  console.log(x);
}

Let’s create two variables a and b. Whatever we pass into our sayHi function is outputted.

let a = "Hi!";
let b = 10;

sayHi(a); // "Hi!"
sayHi(b); // 10

Quick note: parameter and argument are often used interchangeably online but they are not the same thing. A parameter is the variable in the function declaration. That is x here. The argument is the actual value that is passed to the function, which is a in the first case and then b in the second one.

In JavaScript we can also pass functions as parameters. So we can do this:

function sayHi(x) {
  console.log(x);
}

function sayBye() {
  console.log("Bye!")
}

sayHi(sayBye()); // "Bye!"

For the parameter x we have passed in the function sayBye and immediately called it using (). That is why we pass in sayBye() not simply sayBye.

sayBye is a callback function because it was passed in as a parameter. That’s it.

The confusing part about callback functions is not what they are but how they are used. Generally they are used to indicate when something happened and that something is often called an “event.” Events happen all the time when manipulating the DOM, for example when a mouse click occurs. And this situation is perfect for a callback function because we want our function available but not called until an action is taken.

Consider if we wanted a button to alert “Lasers activated!!!” when clicked. We can create an HTML button element and use the native onclick event. The value of this event will be a callback function activateLasers(). So when the button is clicked, activateLasers() is also called and adds an alert to our screen.

See the Pen JavaScript Callbacks Explained by William Vincent (@wsvincent) on CodePen.

Conclusion

And that’s really it. A callback function is when we pass a function as an argument into another function. This is often used around DOM events and it allows for asynchronous behavior.




Want to improve your JavaScript? I have a list of recommended JavaScript books.