Object Literal Syntax Extensions in JavaScript

📌 What Are Object Literal Syntax Extensions?

Object literal syntax extensions are modern features added to JavaScript’s object literal notation that make it easier and more concise to create and work with objects. Introduced mainly in ES6, these extensions improve readability and reduce boilerplate. 🚀

⚙️ Key Extensions Overview

  • Shorthand Property Names
  • Method Definitions
  • Computed Property Names
  • Property Value Shorthand

🧩 Shorthand Property Names

When the property name matches the variable name, you can omit the value:

Before ES6

const name = "Alice";
const age = 25;

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

With Shorthand Property Names

const name = "Alice";
const age = 25;

const person = { name, age };

console.log(person); // { name: "Alice", age: 25 }

🧑‍💻 Method Definitions

You can define methods without the function keyword:

Traditional vs Shorthand Methods

const obj = {
  // Traditional
  greet: function() {
    console.log("Hello!");
  },

  // Shorthand
  sayBye() {
    console.log("Goodbye!");
  }
};

obj.greet();  // Hello!
obj.sayBye(); // Goodbye!

🔮 Computed Property Names

Use square brackets to define property names dynamically:

Computed Property Names

const prop = "score";

const player = {
  [prop]: 100
};

console.log(player.score); // 100

✨ Combined Example

Object Literal with Extensions

const firstName = "John";
const lastName = "Doe";
const key = "age";

const person = {
  firstName,
  lastName,
  [key]: 28,
  greet() {
    console.log(`Hi, I'm ${this.firstName} ${this.lastName}.`);
  }
};

person.greet(); // Hi, I'm John Doe.
console.log(person.age); // 28

🧠 Benefits

  • Less code to write and read ✅
  • Dynamic property names for flexible objects 🔄
  • Clearer and cleaner method definitions 🧹

📚 Learn More

>>“Modern object literals let you write expressive and concise code effortlessly.” ✨