callback function example

I agree with you, the code in the snippet is very unclear.

The answers you got are great, however none refers to the actual use of callback in your code, and I would like to reference that specifically.

First, I will answer your question, and then I will elaborate on the complexity of it.

The answer

turns out socket.io are doing something very cool which is not the standard I know.. socket.io are passing the callback from the front-end to the backend!

So to answer your question what is this callback function - you have to look at your frontend code.

Look for code that looks like this

  socket.emit('new user', data, function( booleanParameter ){
        // what are you doing with booleanParameter here?
  });

I assume that in your case true/false values are meant to pass back to the frontend if new user was added (true) or not (false)..

Or perhaps if the nickname is already in use or not so that the frontend can show an error string if it is..

Basically, @SumanBogati was right in his answer, but I felt it was lacking the step of finding the callback in the front-end due to socket.io's special treatment.

Further Suggestion To make your code clearer

  • Change name of parameter data to nickname
  • Add comments - why are you placing nickname on socket?
  • add documentation

Use jsdocs to explain what the callback is doing

/**

     @callback NewUserCallback 
     @param {boolean} booleanParameter does something.. 

**/

and then on the function itself

/**
     @parameter {string} nickname 
     @parameter {NewUserCallback} callback
**/

The complexity

Usually, in nodejs, a callback expects the first argument to be an error, so reading your code, it says

socket.on('new user', function(data, callback){
    if (nicknames.indexOf(data) != -1){

        ///// THERE IS NO ERROR

        callback(false);
    }else{

        ///// THERE IS AN ERROR

        callback(true);

        /// do more stuff after the error
        socket.nickname = data;
        nicknames.push(socket.nickname);
        updateUserList();
    }
});

Not the pattern you'd expect, is it? I guess this is why you asked the question.

Still the question remains what socket.io's callback means, right? Perhaps their callback does not expect an error as first argument.

I have never used socket.io, and I was unable to find a documentation to clarify this. So I had to download their chat example and debug it ==> and so the answer I gave, they are passing the function from the frontend to the backend.

Socket.io should definitely stress this point in large font in their documentation under a title named "How does socket.io handle callbacks?" or "How does our callbacks work?".

Great question! Learned a lot from it!


When you pass a function as an argument, it is known as a callback function, and when you return a value through this callback function, the value is a parameter of the passed function.

function myFunction(val, callback){
    if(val == 1){
        callback(true);
    }else{
        callback(false);
    }
}

myFunction(0, 
//the true or false are passed from callback() 
//is getting here as bool
// the anonymous function below defines the functionality of the callback
function (bool){
    if(bool){
        alert("do stuff for when value is true");
    }else {
        //this condition is satisfied as 0 passed
        alert("do stuff for when value is false");
    }
});

Basically, callbacks() are used for asynchronous concepts. It is invoked on a particular event.

myFunction is also callback function. For example, it occurs on a click event.

document.body.addEventListener('click', myFunction);

It means, first assign the action to other function, and don't think about this. The action will be performed when the condition is met.


A callback function, is a function that is passed to another function (let’s call this other function “otherFunction”) as a parameter, and the callback function is called (or executed) inside the otherFunction.

Here is my simple example for callback function

// callback add
function add(a, b){
  console.log(a+b);
}

// Main function
function getInput(cb) {
  c = 5+5;
  d = 6+6;
  if (typeof cb === 'function') {
    cb(c, d);
  }
}

getInput(add)

For detailed explanation refer the this link


I'll try to simplify with a "concrete" example (I hope).

Let's say I have a function that "calculates" the current day and I'll call that function each time I would need the current day ("Don't call us, we'll call you" or whatever).

var getCurrentDay = function (callback) {
    var currDate = new Date();        
    callback(currDate, 'err');
   });
};




getCurrentDay(function (returnDay) {         
    logger.info('Today is: ' + returnDay); });

Tags: