New ECMAScript 2015 Features: Object Literals to Destructuring Assignments

By Rob Gravelle

You may have heard by now that The General Assembly of Ecma International recently announced the approval of the ECMAScript 6 Language Specification. Also known as ECMAScript 2015, the spec has already begun to receive support from browser vendors like Mozilla Firefox. While we're waiting for other vendors to jump on board, we'll be getting better acquainted with some of the exciting new additions to the JS language. This is the second installment in a two-part series that began with New ECMAScript 2015 Features: Arrows to Tail Calls article.

New-and-improved Object Literals

As you are probably aware, object literal notation consists of a list of zero or more name/value pairs, enclosed in curly braces ({}). While that part hasn't changed, a lot of what goes inside those curly braces has!

Shorthand Property Notation

Assigning variables to an object literal has always been more tedious than necessary due to the duplication of the variable names. Now, we can dispense with the name declarations and simply assign the variables directly. We can then reference them just like before using o.a or o[a] accessor notation.

// ES5
var a = "foo", 
    b = 42,
    c = {};

var o = { 
  a: a,
  b: b,
  c: c
};

// ES6 shorthand property names
var a = "foo", 
    b = 42, 
    c = {};

var o = { a, b, c };

Computed Property Names

In ES6, an expression in brackets [] will be evaluated as the property name. This is almost identical the bracket notation of the property accessor syntax (o['myprop']), which we just saw. Up until ES6, you couldn't use that syntax within object literals, so you had to initialize the object and then set computed names after-the-fact:

// ES5
var i = 0;
var o = {
  a: "foo",
  b: 42,
  c: {}
}
o['foo' + ++i] = i;
o['foo' + ++i] = i;
o['foo' + ++i] = i;

// ES6
var i = 0;
var o = {
  a: "foo",
  b: 42,
  c: {},
  ['foo' + ++i]: i,
  ['foo' + ++i]: i,
  ['foo' + ++i]: i
}

Duplicate Property Names

Continuing on the subject of property names, in ECMAScript 5 strict mode, duplicate property names were considered a SyntaxError. ECMAScript 6 has relaxed this restriction, due to the introduction of computed property names making duplication more likely at runtime. Here's a function that puts that change to the test:

function testES6DuplicatePropertyNames(){
  "use strict";
  try {
    var test = { myprop: 1, myprop: 2 };

    // should not throw and error in ES6 because 
    //duplicate property names are allowed in strict mode
    return "ES6";
  } catch (e) {
    // Error thrown in ES5 because duplicates prohibited in strict mode
    return "ES5";
  }
}

Function Shorthand

While perhaps not as mind boggling as close-up photos of Pluto, functions may be expressed without the "function" keyword. Saves some typing!

// ES5
var cart = {
  _items: [],
  addItem: function(item) {
    this._items.push(item);

    return this;
  },
  toString: function() {
    return this._items.join(', ');
  }
}

// ES6
var cart = {
  _items: [],
  //function keyword omitted
  addItem(item) {
    this._items.push(item);

    return this;
  },
  //function keyword omitted
  toString() {
    return this._items.join(', ');
  }
}

Destructuring Assignments

Here's a great time saver for assigning parts of an object to several variables at once. Before ES6 we had no choice but to extract each value via its own assignment. Thanks to Assignment Destructuring, we can do it all in one fell swoop:

var planet = {
  positionFromTheSun: 3,
  radiusInKilometers: 6371,
  rotationTimeInHours: 24,
  yearlyCycle: 365,
  supportsLife: true
};

//ES5 assignment
var positionFromTheSun = planet.positionFromTheSun;
var radiusInKilometers = planet.radiusInKilometers;
var rotationTimeInHours = planet.rotationTimeInHours;
var yearlyCycle = planet.yearlyCycle;
var supportsLife = planet.supportsLife;

//ES6 assignment
var { positionFromTheSun, radiusInKilometers, rotationTimeInHours, yearlyCycle, supportsLife } = planet;

Very nice!

Conclusion

The more I explore ES6's new offerings, the more eager I am getting to use them. Once I do, I'll be sure to share what I learn about them.



Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
  •  
  •  
  •  
Thanks for your registration, follow us on our social networks to keep up-to-date