Enhanced Object Literal in JavaScript

JavaScript has long been known for its simplicity in creating objects using object literals. With the introduction of ECMAScript 6 (ES6), the object literal syntax has been enhanced to provide more concise and expressive ways to define objects. These enhancements include property value shorthand, method definition shorthand, and computed property names. Let's explore these features through an example.

Example: Enhanced Object Literals

Consider the task of creating a ninja object. We want to assign it a property based on the value of a variable in scope, a property whose name is dynamically computed, and a method. The following listing demonstrates how this can be achieved using both the traditional and enhanced object literal syntax.

Listing A.5. Enhanced Object Literals

const name = "Yoshi";
const oldNinja = {
  name: name,                                                        // #A
  getName: function(){                                               // #B
    return this.name;
  }
};

oldNinja["old" + name] = true;                                       // #C
assert(oldNinja.name === "Yoshi", "Yoshi here");
assert(typeof oldNinja.getName === "function", "with a method");
assert("oldYoshi" in oldNinja, "and a dynamic property");


const newNinja = {
  name,                                                              // #D
  getName(){                                                         // #E
    return this.name;
  },
  ["new" + name]: true                                               // #F
};

assert(newNinja.name === "Yoshi", "Yoshi here, again");
assert(typeof newNinja.getName === "function", "with a method");
assert("newYoshi" in newNinja, "and a dynamic property");

Explanation

  1. Property Value Shorthand (Line #D): In the newNinja object, the property name is assigned the value of the variable name without explicitly specifying name: name. This shorthand syntax is possible when the property name is the same as the variable name.

  2. Method Definition Shorthand (Line #E): The getName method in the newNinja object is defined without the function keyword and colon. This shorthand makes the code cleaner and more readable.

  3. Computed Property Names (Line #F): The property name ["new" + name] is dynamically computed. This allows for the creation of property names based on expressions, which can be particularly useful for creating properties with dynamic names.

Comparison with Pre-ES6 Syntax

The oldNinja object demonstrates the traditional way of defining objects before ES6. It uses explicit property assignments and method definitions, as well as manually adding computed properties after the object is created. The enhanced syntax in newNinja provides a more concise and expressive way to achieve the same result.

These enhancements to object literals in ES6 make JavaScript code more succinct and maintainable, allowing developers to write cleaner and more efficient code.