5. Object Literal Extensions

ES6 allows declaring object literals by providing shorthand syntax for initializing properties from variables and defining function methods. It also enables the ability to have computed property keys in an object literal definition.

  1. function getCar(make, model, value) {
  2. return {
  3. // with property value shorthand
  4. // syntax, you can omit the property
  5. // value if key matches variable
  6. // name
  7. make, // same as make: make
  8. model, // same as model: model
  9. value, // same as value: value
  10. // computed values now work with
  11. // object literals
  12. ['make' + make]: true,
  13. // Method definition shorthand syntax
  14. // omits `function` keyword & colon
  15. depreciate() {
  16. this.value -= 2500;
  17. }
  18. };
  19. }
  20. let car = getCar('Kia', 'Sorento', 40000);
  21. console.log(car);
  22. // {
  23. // make: 'Kia',
  24. // model:'Sorento',
  25. // value: 40000,
  26. // makeKia: true,
  27. // depreciate: function()
  28. // }