Wednesday 22 February 2012

JavaScript: Object literals - object initializers

Question:
How to create a simple JavaScript object with object initializers (aka object literals)?


Answer:
You can create objects on the fly using object literals (initalizers).
The advantage is, that you don't need a constructor function.
For simple problems this is the easiest solution.

Here is an example
var myObj = { 
   prop_1: "value_1",
   2: "value_2", 
   "hi there": 222,
   f: function(){return 1;}
};

console.log(myObj.prop_1);     // value_1
console.log(myObj["prop_1"]);  // value_1
console.log(myObj[2]);         // value_1
console.log(myObj["hi there"]);// 222
console.log(myObj.f());        // 1
 

Identifiers and values are separated by colon ':'.
Different properties are separated by comma ','.

Identifiers (left side) can be standard identifiers (start with letter, then alpha, can contain underscore), numbers and strings.
Values can be of any JavaScript type: string, number, date, object, function etc.

You could have also created an empty object and then augment it.
// create an empty object
var myObj = {}; 

// add property using identifier
myObj.prop_1 = "hello";
// add property using a number
myObj[2] = 200;
// add property using a string
myObj["hi there"] = "Coucou";
// add a function property
myObj.f = function(){return 1;}
 

No comments: