Search⌘ K
AI Features

Enhanced Object Literals

Explore how enhanced object literals simplify creating and managing JavaScript objects by using shorthand property assignments, method definitions, and computed properties. Understand how these features reduce boilerplate and improve code readability, enabling you to write cleaner and more concise JavaScript code.

Traditional way of creating an object

Creating an object by assigning fields with values from existing variables is a common operation. In the past, this process involved a lot of noisy code.

Example

Let’s use the old way to create an object with a few fields and methods.

Javascript (babel-node)
'use strict';
//START:CODE-1
const createPerson = function(name, age, sport, sportFn) {
const person = {
name: name,
age: age,
toString: function() {
return this.name + ' ' + this.age;
}
};
person['play' + sport] = sportFn;
return person;
};
const sam =
createPerson('Sam', 21, 'Soccer',
function() { console.log(`${this.name}, kick, don't touch`); });
//END:CODE-1
//START:CODE-2
console.log(sam.name);
console.log(sam.toString());
sam.playSoccer();
//END:CODE-2

Example explanation

  • The createPerson() function receives a few parameters and uses them to create an object.

  • Next, it assigns the value of name to a property with the same name and, likewise, assigns age to age.

  • Finally, it creates a computed property whose name is based on the value of the sport parameter. Previously, this last step was done outside of the initialization because computed properties were not allowed in the object initialization list.

  • As you can see from the above output, the code works.

However, this example ...