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.
Example explanation
-
The
createPerson()function receives a few parameters and uses them to create an object. -
Next, it assigns the value of
nameto a property with the same name and, likewise, assignsagetoage. -
Finally, it creates a computed property whose name is based on the value of the
sportparameter. 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 ...