Search⌘ K
AI Features

Creating an object literal

Explore creating JavaScript objects through object literals using braces, the new operator, and the create method. Understand how to define properties and functions within objects and how const affects object assignment.

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 {..}:

Javascript (babel-node)
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 ...