ES6: Enhanced Object Literals
4min read
ES6 brings us a better version of object literals. We will write less code to reach the same result.
No repetition: key-value
Sometimes we want to create objects on the fly with dynamic values. We can use functions to achieve this by passing them arguments and return objects from them. The object-factory-function needs to initialize the objects with properties. It is quite common to use the same placeholder-name for the key : value pair in such a case. The enhanced object literals in ES6 allow us to just write the placeholdername as the initialized property on the object if key and value pair are the same.
ES5
ES6
No repetition: methods
Not only key-value pairs can be written short but also methods receive a more concise syntax update. Instead of writing…
…we can shorten it to:
ES5
ES6
Use variables as keys
ES5
ES6
We can use the short-syntax for writing key-value pairs except for the dynamic added [key1] which has to be written in the classical way.
Dynamic keys [key1] can be combined with incrementable variables in order to make the keys even more dynamic.
Leave a Reply
Want to join the discussion?Feel free to contribute!