The best way to place callback definition In JavaScript we can write callback definition in  many different ways:

Definition after usage:

var fs = require('fs')
fs.readFile('movie.mp4', finishedReading)

function finishedReading(error, movieData) {
  if (error) return console.error(error)
  // do something with the movieData
}


Definition before usage:

var fs = require('fs')

function finishedReading(error, movieData) {
  if (error) return console.error(error)
  // do something with the movieData
}

fs.readFile('movie.mp4', finishedReading)


In-line definition:

var fs = require('fs')

fs.readFile('movie.mp4', function finishedReading(error, movieData) {
  if (error) return console.error(error)
  // do something with the movieData
})


Which way is the best for code readability and maintainability?
In my opinion, if you use the same callback multiple times, or if the callbacks are similiar enough to be extracted and called with parameters, they should be extracted to keep DRY principle. In this case for me this does not make much difference if the callback was defined before first call, after it, or even if it exists in some other file, provided I can easily find it - and editors do help with that. For me there is slight preference to callback definition after the call, see below.

In case of single-use callbacks, I personally prefer to read them in-line. Let's consider these three options and how my brain works with them:


callback inline: I'm reading through the code in one go, learning what happens once the calling back action finishes;
callback definition after call: I perform mental GOTO, jumping to definition in order to understand what happens;
callback definition before call: I either skip it until I need it and make the same mental GOTO at some point later, or read through trying to remember and keep in mind what the callback does before I even know if and when it would be needed. I guess this could be called 'mental label' for the sake of consistent terminology.


I am lazy and prefer not to strain my brain trying to juggle multiple informations and contexts in order not to let them slip from short-term memory.