Sitemap
Yogesh Satale

Yogesh Satale

Press enter or click to view image in full size

JavaScript advanced Feature(Callback Functions)

2 min readApr 26, 2020

We are learning below:

1. What is Callback?

2. When we use callback?

What is Callback?

Callback function you can pass functions as argument to another function and inside that host function you would execute that past function at some point.

e.g.

const host = function(cb){

console.log(1);

cb();

}

const callback = function(){

console.log(“you called me back from host” )

}

host(callback);

/output :
1
you called me back from host

There is two types of function declaration and function expression

A function definition (also called a function declaration, or function statement) consists of the function keyword

e.g. function square(number) {

return number * number;

}

Function expression can be anonymous; it does not have to have a name

They are saved inside the variable.

e.g. const square = function(number) { return number * number }

Why we use this and when we use this callback?

Lets look at simple example.

Now first we use simple function and then we use callback function

const calc = function(operator, num1, num2){

if(operator === ‘+’ ){

return num1 + num2;

}

if(operator === ‘-’ ){

return num1 — num2;

}

Get Yogesh Satale’s stories in your inbox

Join Medium for free to get updates from this writer.

if(operator === undefined){

return console.log(“ I don’t know what to do “);

}

}

let result = calc(‘+’,2,1);

console.log(result)

/output : 3

let result = calc(‘undefined’,2,1);

console.log(result);

/output : I don’t know what to do

So now we are using callback function convert to simple way.

let add = function(a,b)

{

return a+b;

}

let mult = function(a,b)

{

return a*b;

}

let power = function(a,b)

{

return a**b;

}

const calc = function(calFunction, num1, num2){

calFunction( num1, num2)

}

let result = calc(add,2,1);

console.log(result)

/output : 3

let result1 = calc(mult,2,1);

console.log(result1)

/output : 2

let result2 = calc(power,2,2);

console.log(result2)

/output : 4

--

--