Creating an object literal

This lesson teaches different ways to create object literals in JavaScript.

Introduction

Just like other variables in JavaScript, an object also has to be defined and initialized to be created. There are various ways to create an object.

An object literal can be created:

  • using the figure brackets {...} in the declaration.

  • using the new keyword.

  • based on an existing object by using the create() method.

All of these approaches do exactly the same thing.

Syntax

Figure Brackets

We discussed earlier that an object contains data values and functions known as its properties. Let’s take a look at the syntax for creating an object literal using {..}:

Press + to interact
var objectName = {
//properties defined
propertyName1 : propertyValue1,
propertyName2 : propertyValue2,
functionName() {}
}

As shown above, to define a property value, the name of the property needs to be written first followed by a colon and then the property value.

A property value can ...

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy