...

/

Enhanced Object Literals

Enhanced Object Literals

Get introduced to the enhanced object literal and see how to create properties and methods with examples.

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.

Press + to interact
'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 ...

Access this course and 1400+ top-rated courses and projects.