The callback function is a must-know concept for developers! 

What is a function() ?

A function is a block of code that does a defined task when called. Functions can be useful for doing tasks in an organized manner. 

Suppose we want to greet everytime a user logs into his account.

Here is a simple example1 of a function that when called, greet John.

function greet(name) {
    console.log(`Morning ${name}`);
}

greet('John'); // Hi John

In the above javascript function example, we have passed string value, John, to the function as an argument or sometimes called actual parameter.

A function can have one or many parameters. In the below example2, we have two parameters firstName and lastName. The function greet accepts these two arguments and concatenates them to print the user's full name.

function greet(firstName,lastName) {
    console.log(`Morning ${firstName} ${lastName}`);
}

greet('John', 'Doe'); // Hi John Doe

 

JavaScript has many built-in functions like seTimeOut()prompt()etc.

What is a callback function?

JavaScript can accept a function as an argument in another function. So this means, a function that is passed as an argument in another function is a callback function. The callback function executes after another function has executed.

In JavaScript, functions are objects and as a regular object, they can be passed to another function.

Let's see an example3 using JavaScript built-in method setTimeout -

function greet(firstName,lastName) {
    console.log(`Morning ${firstName} ${lastName}`);
}
// Greet after 5 seconds 
setTimeout(greet('John', 'Doe'), 5000)

In other words, we call one function and instruct it that once you are finished executing call this other function and execute it. That other function is a callback function.

function doSomething(greetAgain) {
   // alert('ok')
   //...
   greetAgain();

}

// The 'other function'
function sayHi () {
   console.log('Hi there!')
}

doSomething(sayHi)

The above code snippet has a function doSomething and takes another function as an argument. We pass sayHi function as an argument and this is our callback function.

Let's see another example4 of a JavaScript Callback function.

// Array of natural numbers
let numbers = [1, 2, 3, 7, 8, 10]

// check for even numbers
function evenNumbers(number) {
    return number % 2 === 0;
}

// Filter even numbers from natural numbers by passing evenNumber() to filter()
const filterEvenNumbers = numbers.filter(evenNumbers);

console.log(filterEvenNumbers) // [2, 8, 10]

Here we passed evenNumber as an argument in JavaScript built-in filter function. So, the function evenNumber is a callback function and so does the greet() in example 3.