What is callback in javaScript

Views

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; 	
	})); 

How To Write and Run Your Firs …

How To Write and Run Your First Program in Node.js. Node.js is a popular open-source runtime environment that can execute JavaScript outside of the browser using the V8 JavaScript engine, which is the same engine used to power the Google Chrome web b …

read more
Views

Getting Started with PM2, the …

Getting Started with PM2, the Node.js Process Manager. PM2, or Process Manager 2 is an incredibly versatile production process manager written in Node.js.Restarting after crashes: PM2 allows us to keep processes running until the heat death of the un …

read more
Views