ES6 introduced several improvements to object literals in JavaScript:

  1. Property shorthand
  2. Method shorthand
  3. Computed property names
  4. Shorthand for prototypes / super
  5. Concise notation for object destructuring defaults (combined with literals)

1. Property Shorthand

Before ES6, if the property name and variable name were the same, you had to write:

const name = "Zaman";
const age = 25;
const user = {
name: name,
age: age
};

ES6 Simplification (Property Shorthand):

const name = "Zaman";
const age = 25;
const user = { name, age };
console.log(user); // { name: "Zaman", age: 25 }

Cleaner and shorter.

2. Method Shorthand

Before ES6:

const user = {
greet: function() {
console.log("Hello!");
}
};

ES6 Method Shorthand:

const user = {
greet() {
console.log("Hello!");
}
};
user.greet(); // Hello
  • Works with super in class-like objects
  • Cleaner syntax, especially for multiple methods

3. Computed Property Names

Sometimes you want dynamic property names. Before ES6, you had to use bracket notation after object creation:

const propName = "age";
const user = {};
user[propName] = 25;

ES6 allows computed property names directly in object literal:

const propName = "age";
const user = {
[propName]: 25
};
console.log(user.age); // 25

  • Can also compute names dynamically:
const prefix = "user_";
const id = 1;
const user = {
[prefix + id]: "Zaman"
};
console.log(user.user_1); // Zaman

4. Object Destructuring with Defaults and Shorthand

You can combine destructuring with property shorthand:

function createUser({ name, age = 18 }) {
return { name, age }; // shorthand
}
const user = createUser({ name: "Zaman" });
console.log(user); // { name: "Zaman", age: 18 }

5. Example: Combining Extensions

const key = "role";
const role = "Admin";
const firstName = "Zaman";const user = {
firstName, // property shorthand
[key]: role, // computed property
greet() { // method shorthand
console.log(`Hi, ${this.firstName}, your role is ${this.role}`);
}
};

user.greet(); // Hi, Zaman, your role is Admin

6. Real-world Use Case: Dynamic Object Creation

function createUser(id, name, role) {
return {
id,
name,
[role]: true,      // dynamic property
greet() {
console.log(`${name} has role: ${role}`);
}
};
}
const user1 = createUser(1, "Zaman", "admin");
user1.greet(); // Zaman has role: admin
console.log(user1.admin); // true

Categorized in:

Javascript ES6,