This is probably a stupid noob question but what does the : represent in the following context:
var stuffToDo = {
\'bar\' : function() {
alert(\'
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:
Conditional (ternary) operator [MDN]:
var val = condition ? true-value : false-value;
Labels [MDN]:
someLabel: var x = 5;
It is the object literal notation http://www.dyn-web.com/tutorials/obj_lit.php