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.

asked Dec 30, 2016 at 10:28
3
  • What makes you think that it is passed last in most cases. Can you give some example Commented Dec 30, 2016 at 10:30
  • May be its most complex or different type of argument , people tend to add in last Commented Dec 30, 2016 at 10:31
  • In asynchronous function and mostly in Node js we generally use function(req, res, next){} where next is the callback function. Commented Dec 30, 2016 at 10:34

2 Answers 2

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');
});
answered Dec 30, 2016 at 10:34
Sign up to request clarification or add additional context in comments.

Comments

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

answered Dec 30, 2016 at 10:33

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.