Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
177
rated 0 times [  181] [ 4]  / answers: 1 / hits: 16889  / 13 Years ago, mon, august 22, 2011, 12:00:00

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?


More From » javascript

 Answers
20

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:




[#90492] Friday, August 19, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ramseydeshaunc

Total Points: 30
Total Questions: 91
Total Answers: 103

Location: Palau
Member since Tue, May 30, 2023
1 Year ago
;