JavaScript Objects

JavaScript objects are variables that can contain many values. The values are written as name:value pairs (name and value separated by a colon). An object can be created with curly brackets with an optional list of properties. A property is a "key: value" pair, where key is a string (property name), and value can be anything.

Creating Object

You can create an empty object in JavaScript in two ways:

1. Using the new keyword, as:

var star = new Object; // object constructor syntax

2. Using curly braces, as:

var star = {}; // object literal syntax

Properties of Objects

After creating an object, you can start assigning properties and methods to it. For example:

star.name = "Polaris";
star.constellation = "Ursa Minor";

To walk over all keys of an object, there exists a special form of the loop: for..in. With a for...in loop, you can loop through each of the properties in an object.

for (var element in star) {
for (var propt in star[element]) {
alert(element + ": " + propt + " = " + star[element][propt]);
}
}

Looking for a property

Sometimes you don't want or need to loop through every property. Sometimes you just want to know whether a given property already exists within an object. You can use the in operator to test for the property, as in:

if (property in object) {
// do something here
}

Adding Methods to Objects

A function that is the property of an object is called its method. In the same way you can add properties to self-defined objects, you can add methods. For example:

function Star(constell, type, specclass, magnitude) {
this.constellation = constell;
this.type = type;
this.spectralClass = specclass;
this.mag = magnitude;
this.show = function() {
alert("hello, this is a method.");
}
}

An object method needs to access the information stored in the object to do its job. To access the object, a method can use the this keyword.

To call the method, you write code that looks like this:

star["Polaris"].show();

Built-in Objects

The JavaScript language makes several useful objects available to assist with tasks common to the JavaScript program.