— JavaScript, beginner, tutorial, learn-modern-javascript — 1 min read
By the end of this tutorial, you will be able to:
ES6 offers enhanced object literals, including shorthand syntax for method definition and property values, and dynamic property keys.
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// ES52function getCar(make, model, year) {3 return {4 make: make,5 model: model,6 year: year,7 };8}9
10// ES611function getCar(make, model, year) {12 return {13 make,14 model,15 year,16 };17}
1// ES52var 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// ES613const 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};
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"
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!