Object initializers in ES6

There is a Mobile Optimized version of this page (AMP). Open Mobile Version.

A situation that comes up a lot in my JavaScript code:

  • var tvShow = {
    • id: id,
    • title: title,
    • network: network
    • }

As you type it you think geez there’s got to be a better way, and in the new version of JavaScript, there is.

  • var tvShow = {
    • id,
    • title,
    • network
    • }

Since usually the only thing you’re going to do is pass it off to a subroutine to save it in a file or database, you could do it this way:

  • saveShow ({id, title, network});

In the old more cumbersome notation you probably wouldn’t do this, but now I find I do, esp if there is only one property to initialize.

I guess the bottom line is I don’t mind two ways to do something if the new way is a simplified version of the old way.

Read More