How to use JavaScript Object Literals? [SOLVED]


Olorunfemi Akinlua

JavaScript

Introduction

In JavaScript, there are different literals from array literals to string literals. It’s pretty much a fanciful word for values. So, we have array values, string values, and object values. Literals are fixed values that we provide within our code, and object literals are simply just the property name and the corresponding values.

In this article, we will discuss object literals in JavaScript.

 

Features of JavaScript Object Literals

Object literals in JavaScript are a way to create objects using a simple notation. Some of the key features of object literals in JavaScript include:

  1. Property-value pairs: Object literals consist of a set of property-value pairs, where each property is a string and the value can be any valid JavaScript value, including another object.
  2. Shorthand property names: In ES6, when the property name is the same as the variable name, you can use shorthand property names.
  3. Computed property names: In ES6, you can use expressions within brackets [] to compute the property name at runtime.
  4. Method definitions: Object literals can also contain methods, which are functions that are associated with an object.
  5. Property value shorthand: In ES6, when the variable name is the same as the property name, you can use property value shorthand.
  6. Spread operator: In ES6, you can use the spread operator (...) to copy properties of an existing object into a new object.
  7. JSON compatibility: Object literals are also compatible with JSON (JavaScript Object Notation), which is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate.

Example:

const person = {
  name: "John",
  age: 30,
  speak: function(){console.log("Hello")},
  [`address_${1+2}`]: "New York",
  ...otherPerson
};

Object literals provide a simple and flexible way to create objects in JavaScript and are widely used in many different types of applications.

 

Examples using JavaScript Object Literals

Example-1: Create simple Object with properties

In this example we create a simple object called "person" with three properties: "name", "age", and "gender". We then use the dot notation (object.property) to access the values of each property and log them to the console.

const person = {
  name: "Amit",
  age: 30,
  gender: "male"
};
console.log(person.name);  // "Amit"
console.log(person.age);   // 30
console.log(person.gender);  // "male"

 

Example-2: Creating an object with methods

In this example we create an object called "calculator" with two methods, "add" and "subtract". These methods take in two arguments and return the result of the corresponding mathematical operation. We then use the dot notation to call these methods and pass in the required arguments, and log the result to the console.

const calculator = {
  add(a, b) {
    return a + b;
  },
  subtract(a, b) {
    return a - b;
  }
};
console.log(calculator.add(1, 2)); // 3
console.log(calculator.subtract(5, 3)); // 2

 

Example-3: Using shorthand property names and property value shorthand

In this example, we use shorthand property names and property value shorthand to create an object called "coordinates" with properties "x" and "y" that have the same value as the variables "x" and "y". We then use the dot notation to access the values of each property and log them to the console.

const x = 5;
const y = 10;
const coordinates = { x, y };
console.log(coordinates.x); // 5
console.log(coordinates.y); // 10

 

Example-4: Using computed property names

In this example, we use computed property names to create an object called "obj" with properties "name" and "age_10". The property key of "name" is computed from the variable "key" and the property key of "age_10" is computed from the expression "age_" + 10. We then use the dot notation to access the values of each property and log them to the console.

const key = "name";
const obj = {
  [key]: "Amit",
  ["age_" + 10]: 30
};
console.log(obj.name);  // "Amit"
console.log(obj.age_10);  // 30

 

Example-5: Using the spread operator to copy properties from one object to another

In this example, we use the spread operator to create a new object called "newPerson" by copying all the properties from the existing object "person" and adding a new property "gender" with a value of "male". We then log the new object to the console.

const person = { name: "Amit", age: 30 };
const newPerson = { ...person, gender: "male" };
console.log(newPerson);  // { name: "Amit", age: 30, gender: "male" }

 

Example-6: JSON compatibility

In this example, we create a JSON string that represents an object, then use the JSON.parse() method to convert the JSON string into a JavaScript object, then we can use the dot notation to access the properties.

const personJSON = '{"name": "Amit", "age": 30}';
const person = JSON.parse(personJSON);
console.log(person.name);  // "Amit"
console.log(person.age);   // 30

 

Summary

Object literals are a powerful feature of JavaScript that allow you to create objects with properties and methods in a simple, concise way. They can be used for various purposes, such as storing data, creating classes, and more.

 

References

Literal - MDN Web Docs Glossary: Definitions of Web-related terms | MDN (mozilla.org)

 

Views: 1

Olorunfemi Akinlua

He is boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital experiences across various domains. You can connect with him on LinkedIn.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment

GoLinuxCloud Logo


We try to offer easy-to-follow guides and tips on various topics such as Linux, Cloud Computing, Programming Languages, Ethical Hacking and much more.

Programming Languages

JavaScript

Python

Golang

Node.js

Java

Laravel