Javascript - Object Type and Creation

Introduction

There are two ways to create an instance of Object.

The first is to use the new operator with the Object constructor like this:

var person = new Object();
person.name = "First";
person.age = 29;

The other way is to use object literal notation.

For example, the following defines the same person object from the previous example using object literal notation:

var person = {
    name : "First",
    age : 29
};

In this example, the left curly brace { signifies the beginning of an object literal.

Property names can also be specified as strings or numbers when using object literal notation:

var person = {
    "name" : "First",
    "age" : 29,
    5: true
};

This example produces an object with a name property, an age property, and a property "5".

Numeric property names are automatically converted to strings.

You can create an object with only the default properties and methods using object literal notation by leaving the space between the curly braces empty:

var person = {};    //same as new Object()
person.name = "First";
person.age = 29;

Related Topics