JavaScript: Enhanced Object Literals (In-Depth)

Enhanced object literals (introduced in ES2015/ES6) make it easier and more concise to write and manage objects in JavaScript.

Key Features

Property Shorthand

let x = 10, y = 20;
let point = { x, y };
// Equivalent to: { x: x, y: y }
    
// Output:
{ x: 10, y: 20 }

Method Shorthand

let person = {
  name: "Alice",
  greet() {
    return "Hello, " + this.name;
  }
};
// Equivalent to greet: function() { ... }
    
// Output:
"Hello, Alice"

Computed Property Names

let key = "score";
let player = {
  [key]: 42,
  ["level" + 1]: "Beginner"
};
    
// Output:
{ score: 42, level1: "Beginner" }

Combining All Features

let kind = "shark";
let animal = {
  kind,
  ["fin" + "Count"]: 2,
  swim() { return "Swimming..."; }
};
    
// Output:
{ kind: "shark", finCount: 2, swim: ƒ }

Benefits

Practice: Use enhanced object literals in your functions, classes, and when returning objects from functions for cleaner code!