Callback function in JavaScript

 Callback Function

The function pass into another function as an argument is called callback function. but the callback function are very powerful in JavaScript. It gives to the access of whole asynchronous word in a synchronous single threaded language.

function a(y){
    console.log('this is a function')
    console.log(y)
}
a(function y(){
    console.log('this is y function')
})

JavaScript is a synchronous single threaded language. it can only do one thing at a time and specific order. but due to callback we can do async things in JavaScript.

setTimeout(function () {
    console.log('Timer');
}, 5000);
function x(y) {
    console.log('x')
    y()
}
x(function y() {
    console.log('y')
})
What happened in this program?
    JavaScript is a single threaded language. that is code will run at a time in specific order. First register a setTimeout(), means it take some callback function and store in a separate memory location and attach to timer 5000ms to it.
    and JavaScript won't wait so it goes to next code and execute it. after this 5000ms will expired then this callback function executed.

Simple Example
const received = document.querySelector('h1');

function add(a, b, display){
    result =  a + b;
    display(result);
}

function display(result){
    received.innerHTML = result
    console.log(result)
}

add(1,2, display);