DEV Community

PUSHAN VERMA
PUSHAN VERMA

Posted on

CallBacks in JavaScript

//Call back functions -Any function that is passed as an argument to another function is known as Callback function.

function printFirstname(firstname,cb,cb2)
{

//cb recieves Lastname function
//cb2 recieves printage function
Enter fullscreen mode Exit fullscreen mode

console.log(firstname);
cb("Verma")
cb2(22);
}

function printLastname(lastname)
{
console.log(lastname);
}

function printAge(age)
{
console.log(age)
}

printFirstname("Pushan",printLastname,printAge);

//👉ans->
//Pushan
//Verma
//22

2nd example:

const fs =require('fs');

console.log("before");
// let data =fs.readFileSync('f1.txt');

fs.readFile('f1.txt',cb);
fs.readFile('f2.txt',cb2);

function cb(err,data)
{
if(err)
{
console.log(err);
}
console.log(" "+data);

}

function cb2(err,data)
{
if(err)
{
console.log(err);
}
console.log(" "+data);

}

console.log("after");

// 👉 ans ->
// before
// after
// this is file 2
// this is file 1

📌HandWritten Notes:
https://github.com/pushanverma/notes/blob/main/webd/Callbacks%20in%20Js%20.pdf

Top comments (0)