What is callback in javaScript

Callback in JavaScript

Callback is also called the higher order function in javaScript.

 

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

 function greeting(name) {   
alert('Hello ' + name); 
}  

function processUserInput(callback) {   
var name = prompt('Please enter your name.');   
callback(name); 
}  

processUserInput(greeting); 

The above example is a synchronous callback, as it is executed immediately.

 let x = function(){ 
console.log("I am called from inside a function"); 
}; 

let y = function(callback){ 
console.log("Do something"); 
callback(); 
}; 

y(x); 

Multiple callabcks

 let add = function(a,b){ 
return a+b; 
}; 

let multiply = function(a,b){ 
return a*b; 
}; 

let substraction = function(a,b){ 
return a-b; 
} 

let calculate = function(num1,num2,callback){ 
return callback(num1,num2); 
} 

console.log(calculate(5,3,add)); 

Anonymous callback function

 let calculate = function(num1,num2,callback){ 
return callback(num1,num2); 
} 

console.log(calculate(5,3,function(a,b){ 
return a*b; 
})); 

Explain the concept of streams in Node.js. How are they used, and what are …

In Node.js, streams are powerful mechanisms for handling data transfer, especially when dealing with large amounts of data or performing I/O operations. Streams provide an abstraction for handling data in chunks, rather than loading entire datasets i …

read more

How To Work With Zip Files in Node.js

Working with zip files in Node.js involves using third-party libraries as Node.js doesn't provide built-in support for zip file manipulation. One of the popular libraries for handling zip files in Node.js is adm-zip. Below are the steps to work with …

read more