Code Highlights logo

Learn

Objects

Creating Object Literals

Object literals provide a straightforward way to define key-value pairs and create objects in a single statement. This can be particularly useful when you want to create a single instance of an object with specific properties and values.

Syntax

To create an object literal, you use the curly braces {}. Inside the curly braces, you define the properties of the object using the key: value syntax. The key represents the name of the property, and the value represents the value assigned to that property.

1let myObject = {
2 key1: value1,
3 key2: value2,
4 // ...
5};

Example

Let's take a look at an example to see how object literals are used:

1let person = {
2 name: "John Doe",
3 age: 30,
4 profession: "Software Developer"
5};

In this example, we have created an object literal called person. It has three properties: name, age, profession, and greet. The name and profession properties store string values, whitle the age is stored as a number.


Instructions

1.

Define a variable called car and assign it an empty object literal {}. This is our starting point for creating our car object.

2.

Add the following properties to the car object:

  • make with a value of "Toyota"
  • model with a value of "Camry"
  • year with a value of 2020
  • color with a value of "blue"

Sign up to start coding

Already have an account?

Sign In

Course content