When a function accepts another functions as an argument, the contained function is called the callback function.

Using callback functions is a core functional programming concept.

Node is basically built up to be asynchronous in everything it does.
That is the reason why callbacks are excepted as arguments rather than returning data in most of the internal Node APIs.

The following code calls readFile (asynchronous method of the file-system)
and once the file is read, callback method will be called.

// callback function.
var fileCallback = function(err, data) {
  if(err) return console.error(err);
  console.log(data);
}

// takes a callback as a parameter. once the readfile is done, callback
// function will be called.
var fs = require('file-system'); // npm install file-system --save
fs.readFile('words.txt', fileCallback);

Another example. In this one we are going to use npm package node-geocoder to get
the latitude and longitude of a particular zipcode.


var NodeGeocoder = require('node-geocoder'); //npm install node-geocoder --save
var options = {
    provider: 'google',
    httpAdapter: 'https',
    formatter: null
};

var geocoder = NodeGeocoder(options);
var data = [];

// takes callback as one of the parameters.
var getGeoData = function(zipcode, callback) {
  geocoder.geocode(zipcode)
  .then(function(res) {
    var lat = res[0]['latitude'];
    var long = res[0]['longitude'];
    data.push(lat);
    data.push(long);
    // return error as null with data as second parameter.
    callback(null,data);
  })
  .catch(function(err){
    // return error with data as null.
    return callback(err,null);
  });
};

var getGeoDims = function(zip) {
  // (err, list) is the callback we are passing.
  getGeoData(zip, ((err, list) => {
    if(err) return console.error(err);
    else return console.log("everything went fine");
  }));
};

getGeoDims(94025);

We invoke the getGeoDims functions. It calls getGeoData function that takes zipcode and callback function as parameters. We could have defined the callback function as in the above example. You can read more about callbacks here.