How to define an object with multiple values in ES6?

In ES6, you can define an object consisting of multiple values using object literals.

Object literal is a concise syntax used to create and initialize objects. By defining objects using curly braces {}, multiple key-value pairs can be defined within the braces, with each pair consisting of a key (property name) and a value separated by a colon (:). Any number of key-value pairs can be defined as needed.

For example, the following code demonstrates how to define an object with multiple values using object literals.

const person = {
  name: 'John',
  age: 30,
  gender: 'male',
  occupation: 'developer'
};

console.log(person);

The above code defines an object called person, which includes attributes such as name, age, gender, and occupation, each with their corresponding values.

The output/result is:

{ name: 'John', age: 30, gender: 'male', occupation: 'developer' }

Instead of directly defining properties and values in the object literal, you can also use variables to define property names and values. For example:

const name = 'John';
const age = 30;

const person = {
  name: name,
  age: age
};

console.log(person);

In the above code, the properties of the person object are defined using the variables name and age. The output remains the same.

{ name: 'John', age: 30 }

It is worth noting that in ES6, a concise syntax can be used when the property name is the same as the variable name. For example:

const name = 'John';
const age = 30;

const person = {
  name,
  age
};

console.log(person);

In the above code, since the attribute name is the same as the variable name, the attribute can be defined directly using the variable name. The output result remains the same.

{ name: 'John', age: 30 }

By using the above method, we can easily define an object consisting of multiple values.

bannerAds