JavaScript

Objects

Objects


Objects

An object is a collection of properties, which are described in the form of key / value pairs.
We can use objects to model "things" using code. For example:

// object definition
var myFirstObject = {
    // add necessary properties
    // pay attention to comma between pairs
    key1: value1,
    key2: value2,
    key3: value3
};

// usage
alert(myFirstObject.key2);

Methods

When an object has a property with a function as the value, it is referred to as a method of that object.

For example, when we use console.log(), log is a method of the console object.
When we use Math.random(), random() is a method of the Math object.

Creating an Object

The following chart demonstrates how we can create objects.

#

There are two main ways to create an object: by using object literal (easiest and most common) and by using object constructor. There are another ways (in ECMAScript6 there are also classes like in other object oriented languages).

Predefined Objects

There are many pre-defined objects in JavaScript. These objects have their pre-defined attributes and methods.
Predefined objects examples:

See MDN Objects for more details.