Difference between "content = function()" and "content: function()"?

Hello all,

So, I have seen this notation in some tutorials as in the example below :

module.exports = React.createClass({
  content: function(){
    // do something
  };
)};

I don’t understand well the notation with “:”. I’m used to define a function in either of the following ways :

var content = function(){ };

function content(){ };

Is it just another way of defining a function, or are there specific cases where you define a function with the “:” ?

You use : because it is a property of an object.

This is just combining Javascript syntax to reduce typing.

If we break this down in pieces it may be easier to see. The “:” is used to make an object in plain vanilla Javascript. For example:

{
    a_property: "blue"
}

You can also assign functions to properties of objects:

function foo() {
    // foo'ing...
}

{
    a_property: "blue",
    a_function: foo
}

If you combine them and directly define your function inside the object:

{
    a_cool_property: "blue",
    a_cool_function: function() {
        // foo'ing...
    }
}

Which is what you are seeing in the tutorials.

1 Like

Hi,

: is used to add a property on a object.Consider :

var person = {}; // person is now an empty object
person.name = 'Alex'; // we add a name property, using "."
person.age = 21;

console.log(person.name + " is " + person.age + " years old"); // Alex is 21 years old

person.talk = function() { console.log('Hello!'); };

person.talk(); // Hello!

You could do exactly the same with this code :

var person = {
  name: 'Alex',
  age: 21,
  talk: function () { console.log('Hello!'); }
};

console.log(person.name + " is " + person.age + " years old"); // Alex is 21 years old
person.talk(); // Hello!
1 Like