JavaScript Objects


Part 3


JavaScript objects

Apart from primitive types such as numbers and strings, everything in JS is an object.

In some ways, an object in JS can be thought of as a collection of key/value pairs, rather like IDictionary<string, object> in .NET.

Objects can be created using object literal syntax:

var customer1 = {
    id: 1,
    name: "John",
    address: "13 Waterwell Lane"
};

or by creating an empty object and then populating it:

var customer2 = {}; // an empty object
customer2.id = 2;
customer2.name = "Linda";
customer2.address: "29 Carlton Road";

You can also set properties using square bracket notation. In this case, the key can be any string you like:

var customer3 = {};
customer3["customer-id"] = 3;
customer3["Customer Name"] = "Brian";
customer3["1st line of address"] = "12 Newark Road";

Getting a property's value can be done using either dot notation or square brackets.

var name1 = customer1.name;
var name2 = customer2["name"];
var name3 = customer3["Customer Name"];   // can't use dot notation for this one

If the object does not contain the specified property, you get undefined.

var age1 = customer1.age;     // undefined

As a result of all this, reflection in JS is very straightforward. To iterate through an object's properties, use a for ... in loop:

var key;
for (key in customer1) {
    alert(key + " => " + customer1[key]);
}

Note that the for ... in loop is NOT like the foreach loop in C#, so you can't use it to iterate through an array.

Objects in JavaScript can be thought of as a collection of key/value pairs.