user595419
user595419

Reputation:

What does the colon (:) in JavaScript represent?

This is probably a stupid noob question but what does the : represent in the following context:

var stuffToDo = {
    'bar' : function() {
        alert('the value was bar -- yay!');
    },

    'baz' : function() {
        alert('boo baz :(');
    },

    'default' : function() {
        alert('everything else is just ok');
    }
};

if (stuffToDo[foo]) {
    stuffToDo[foo]();
} else {
    stuffToDo['default']();
}

Is it storing the function to each of those variables?

Upvotes: 20

Views: 16874

Answers (2)

Felix Kling
Felix Kling

Reputation: 816462

This is an object literal [MDN]:

var obj = {
    key: value
};

// obj.key === value; // true

It assigns value to a property key of obj. While there are no restriction for what value can be (well, it must be something assignable), there are limitations for key: It must be either an identifier name, a string literal or a numeric literal.

More details can be found in section 11.1.5 of the ECMAScript specification.

The literal notation is similar to:

var stuffToDo = {}; // <-- empty object literal

stuffToDo.bar = function() {...};
// or stuffToDo['bar'] = ...

stuffToDo.baz = function() {...};
// or stuffToDo['baz'] = ...

The biggest difference is that when using an object literal, you cannot access other properties of the object during the declaration.

This will not work:

var obj = {
    foo: value,
    bar: obj.foo
};

whereas this does:

var obj = {};
obj.foo = value;
obj.bar = obj.foo;

For completeness, there are two other uses of colons in JavaScript:

Upvotes: 38

gearsdigital
gearsdigital

Reputation: 14205

It is the object literal notation http://www.dyn-web.com/tutorials/obj_lit.php

Upvotes: 4

Related Questions