Creating an object literal

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

Introduction

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

An object literal can be created:

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

  • by 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

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, we first need to write the name of the property followed by a colon and then the property value.

A property value can be anything, such as:

  • string
  • integer
  • boolean
...
Access this course and 1400+ top-rated courses and projects.