Skip to content
Code with Hou

Learn Modern JavaScript - Enhanced Object Literals

JavaScript, beginner, tutorial, learn-modern-javascript1 min read

Introduction

By the end of this tutorial, you will be able to:

  • use the object literal shorthand for initializing property values
  • use the object literal shorthand for writing methods
  • create objects with dynamically computed property keys

Enhanced Object Literals

ES6 offers enhanced object literals, including shorthand syntax for method definition and property values, and dynamic property keys.

Shorthand for initializing property values

ES6 checks if the property key has a corresponding variable name and assigns the value of that variable to the property. If no variable has the same name as the property key defined, an error will be thrown.

1// ES5
2function getCar(make, model, year) {
3 return {
4 make: make,
5 model: model,
6 year: year,
7 };
8}
9
10// ES6
11function getCar(make, model, year) {
12 return {
13 make,
14 model,
15 year,
16 };
17}

Shorthand for writing methods

1// ES5
2var server = {
3 name: "Server",
4 restart: function () {
5 console.log("The" + this.name + " is restarting...");
6 },
7 stop: function () {
8 console.log("The" + this.name + " is stopping...");
9 },
10};
11
12// ES6
13const server = {
14 name: "Server",
15 restart() {
16 console.log(`The ${this.name} is restarting...`);
17 },
18 stop() {
19 console.log(`The ${this.name} is stopping...`);
20 },
21};

Computed property keys

With ES6, the names of object properties in an object literal can be computed dynamically.

1const fieldName = "location";
2
3const formData = {
4 firstName: "Hou",
5 lastName: "Chia",
6 [fieldName]: "Cleveland",
7};
8
9console.log(formData.location); // prints "Cleveland"

Want more content like this? Subscribe to get the latest updates in your inbox

Share your Feedback

What did you like or didn't like about this post? Let me know what worked well and what can be improved. Your feedback is much appreciated!