DEV Community

Cover image for Callbacks in JavaScript
Mursal Furqan Kumbhar
Mursal Furqan Kumbhar

Posted on

Callbacks in JavaScript

Hello, سلام, नमस्ते 👋

We are back again with another essential, crucial and easy to understand topic of JavaScript, that is Callbacks with some examples.

What actually is a Callback?

A function is a block of code, that performs a certain task when called. For example

// function
function welcome(name) {
     console.log('Hi ' + name)
}

welcome('Mursal')
// Output: Hi Mursal
Enter fullscreen mode Exit fullscreen mode

In the above given example, a value is passed as an argument to the welcome() function. You can also pass a function as an argument to a function. This function that is passed as an argument inside of another function, is called a callback function. For example

// function
function welcome(name, callback) {
     console.log('Hi ' + name)
     callback()
}

// callback function
function initCallback() {
     console.log('I am a callback Function')
}

// passing function as an argument
welcome('Mursal', initCallback)
Enter fullscreen mode Exit fullscreen mode

Why use them?

One of the biggest benefit of using Callbacks is you can wait for result of the previous function and then execute another function. For example

// It will show delay in execution
function welcome() {
     console.log('Welcome to Dev')
}

function welcomePerson(name) {
     console.log('Welcome ' + name)
}

// calling the function
setTimeOut(welcome, 2000) //setTimeOut is used to so that the function is delayed
welcomePerson('Mursal')
Enter fullscreen mode Exit fullscreen mode

In the above given example

  • welcome() function is called 2000ms(2s) later
  • During the wait, welcomePerson('Mursal') is executed
  • Welcome Mursal is printed before Welcome to Dev

Delayed GIF

The correct time to use Callbacks

The callback function is helpful when you have to wait for a result that takes time. For example, the data coming from a server since it takes time for data to move.

Go ahead. Try callbacks in your everyday code and share your feedback here.

Top comments (2)

Collapse
 
spiritfox358 profile image
spiritfox358

The article is very awesome

Collapse
 
behrozkamal profile image
Behroz Kamal Khan

Great tutorial discuss about its framework in the upcoming articles