JavaScript Program to Create Objects in Different Ways

To understand this example, you should have the knowledge of the following JavaScript programming topics:


You can create an object in three different ways:

  1. Using object literal
  2. By creating instance of Object directly
  3. By using constructor function

Example 1: Using object literal

Output

object
John
reading
Hello everyone.
90

In this program, we have created an object named person.

You can create an object using an object literal. An object literal uses { } to create an object directly.

An object is created with a key:value pair.

You can also define functions, arrays and even objects inside of an object. You can access the value of the object using dot . notation.


The syntax for creating an object using instance of an object is:

const objectName = new Object();

Example 2: Create an Object using Instance of Object Directly

Output

object
John
reading
Hello everyone.
90

Here, the new keyword is used with the Object() instance to create an object.


Example 3: Create an object using Constructor Function

Output

object
John
reading
Hello everyone.
90

In the above example, the Person() constructor function is used to create an object using the new keyword.

new Person() creates a new object.