8

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.

Arpit Kumar
  • 2,179
  • 5
  • 28
  • 53

2 Answers2

10

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');
});
lenilsondc
  • 9,590
  • 2
  • 25
  • 40
1

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

ExoticChimp
  • 1,884
  • 1
  • 19
  • 37