DEV Community

Codecupdev
Codecupdev

Posted on

Callbacks in JavaScript


What is a callback?
When we pass a function as an argument to another function and that function is invoked within the outer or parent function we are creating a callback. If you have used in-built methods in JavaScript then it is likely that you have already used a callback. Let’s look at a basic example.

function greet(cbFunc) {
  cbFunc();
  cbFunc();
}
function sayHello() {
  console.log("Hello");
}
greet(sayHello);
//Returns --->
'Hello'
'Hello'

Enter fullscreen mode Exit fullscreen mode

In the above example, we create a function declaration called greet which accepts a parameter cbFunc. Inside the function body, the cbFunc gets invoked twice. We then create another function declaration called sayHello and inside the body of this function we console.log Hello. This will be our callback function. We then call the greet function and pass in sayHello as the argument so it becomes the callback function.

When we use callback functions we often use an anonymous function as opposed to an existing function. The reason for this is that if the callback function is not going to be used elsewhere then there is no need to store a named function within the code for the callback. In the following example, we update the code to use an anonymous function:

function greet(cbFunc) {
  cbFunc()
  cbFunc()
}
greet(function() {
  console.log("Hello");
})
//Returns --->
'Hello'
'Hello'
Enter fullscreen mode Exit fullscreen mode

We declare a function declaration called greet which accepts a parameter called cbFunc. This will be the callback function and it gets invoked twice inside the function body. We then call the greet function and pass in the anonymous function directly as the argument. We get the same output when the function runs.

If you have used setTimeout in JavaScript then you have already been using a callback. The setTimeout function accepts a callback and executes this after a certain period of time has passed. Let’s take a look at an example.

setTimeout(() => {
  console.log("Hello");
}, 1000);
//Returns ---> 'Hello'
Enter fullscreen mode Exit fullscreen mode

In the above example, we pass in an anonymous function as a callback to setTimeout. The callback returns a console log that prints the string Hello. After one second this is printed on the screen.

I hope you enjoyed this article. Please feel free to post any comments, questions, or feedback, and follow me for more content!

Top comments (0)