Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why callback is always passed as last parameter JavaScript

In Javascript, I have seen the callback function is passed as the last parameter I am curious why so? Is it a good practice or standard way?

For example:

var doSomething = function(fname, lname, callback){
  console.log("Your name is :"+ fname +" "+ lname);
  callback();
}

var callback = function(){
  console.log("Your name is printed successfully."):
}

doSomething('Arpit', 'Meena', callback); // callback is last parameter here

I know we can pass it at any position and it works but I just want to know the reason behind this.

Thanks.

like image 672
Arpit Kumar Avatar asked Dec 30 '16 10:12

Arpit Kumar


2 Answers

The reason I do this way and have seen others doing so is because of code readability, when you have a calback as the last argument, you can declare the callback inline without making the code unreadable. For example, if you pass the callback as the first parameter:

var doSomething = function(callback, fname, lname){
  console.log("Your name is :"+ fname +" "+ lname);
  callback();
}

You have to call it like:

doSomething(function callback(){
  console.log('foo');
}, 'Arpit', 'Meena');

However, if you use it as the last argument, things are kept much more clear on the function call:

var doSomething = function(fname, lname, callback){
  console.log("Your name is :"+ fname +" "+ lname);
  callback();
}

doSomething('Arpit', 'Meena', function callback(){
  console.log('foo');
});
like image 110
lenilsondc Avatar answered Nov 15 '22 08:11

lenilsondc


It is standard JavaScript convention. Part of the reason it has become standard practice is that it makes things more readable. It's like defining properties at the top of a class - you don't have to but it's standard practice.

Suggested reading: http://technosophos.com/2012/08/22/javascript-callbacks-function-last%E2%80%A6-or-lost.html

http://hancic.info/callback-parameter-should-always-be-last

like image 44
ExoticChimp Avatar answered Nov 15 '22 06:11

ExoticChimp