Lasitha Yapa Lasitha Yapa - 4 months ago 12
Node.js Question

What does "variable : function(){}" means?

In a Node.JS example code I found a code block as follows.

var messageReceivedCallBack = {
onMessageReceived: function (message) {
console.log('Message received ' + message);
}
};


What does this code means? Specifically I can't understand the part with the colon (' : ')

Answer

It's an object literal. That's not a variable, it's a property name:

var foo = {
   a: 1,
   b: 2
};

Is the same as:

var foo = {};
foo.a = 1;
foo.b = 2;

Similarly:

var foo = {
    a: function () {}
};

Is the same as:

var foo = {};
foo.a = function () {};

Therefore the following:

var messageReceivedCallBack = {
    onMessageReceived: function (message) {
        console.log('Message received ' + message);
    }
};

Is just doing this:

var messageReceivedCallBack = {};

messageReceivedCallBack.onMessageReceived = function (message) {
    console.log('Message received ' + message);
};