ES6 Object Enhancements
This is the part of a series of blogs on the new features on the upcoming ECMAScript 6 (ES6) specification which JavaScript implements.
In this blog we focus on the object literal property initialization enhancements introduced in ES6.
Shorthand Creation #
This syntactic sugar allows developers to quickly create objects by merely passing the reference and it’ll create the property based on that. Of course you can’t use reserved words as your property name.
ES5 Version: #
function foo(a, b) {
return {res: "success", a: a, b: b};
}
var a = "foo", b = 42, c = {};
var o = { a: a, b: b, c: c };
ES6 Version: #
function foo(a, b) {
return {res: "success", a, b};
}
var a = "foo", b = 42, c = {};
var o = { a, b, c };
Computed Property Names #
ES6 allows you to dynamically create property names using an expression in brackets [ ]
similar to property accessors.
ES6 Version: #
var param = 'size';
var config = {
[param]: 12,
["mobile" + param.charAt(0).toUpperCase() + param.slice(1)]: 4
};
console.log(config); // { size: 12, mobileSize: 4 }
Method Definition #
ES6 no longer requires you to mention function
over and over again when adding methods to an object.
ES5 Version: #
var cat = {
meow: function(times) {
console.log(Array(times+1).join("meow"));
}
}
ES6 Version: #
var cat = {
meow(times) {
console.log("meow".repeat(times));
// repeat is a built-in String prototype function in ES6
}
}
Default Params #
ES6 also provides default values for parameters to automatically take care of edge cases or whatnot.
ES6 Version: #
var cat = {
meow(times=1) {
console.log("meow".repeat(times));
}
}
cat.meow(); // "meow"
cat.meow(2); // "meowmeow"