Lets talk about object declaration in ES6. It has gotten quite an upgrade from its predecessor, ES5. ECMAScript 6 doesn’t bring any new features in this realm (we aren’t talking about the
class keyword here), but it does have a good amount of new syntax to help us keep all the curly braces at bay.
In this article I’m going to outline all the new ES6 object declaration syntax.
How often have you declared a property function? I know it’s been too many times for me than I care to recall.
ES6 brings in new syntax to shorten this very common declaration pattern. Notice the lack of the
function keyword in the example below! The good thing is that both examples are technically the same thing and could co-exist in ES6.
Defining read only properties using
Object.createProperty() was possible for a pretty long time in ES5. To me it always felt as an afterthought and maybe that’s the reason why you rarely see this feature being used today.
Typing this every time for a readonly property feels like a lot of hassle to me. ES6 introduces proper getter and setter syntax to make this a first class feature:
The difference here is pretty striking. Both examples are equivalent in functionality but ES6 is way more manageable and feels like it belongs. Any attempt to set the
hello property value results in an exception:
Defining a setter is just as easy using the
That translates to the following ES5:
Unlike with the getter, trying to read the value from a set-only property doesn’t throw an error and returns
undefined. I’m not sure how I feel about the difference in behaviour here, at the same time don’t think I’ve ever encountered a set-only property before. I think we can file this under “no big deal”.
Often you have to create an object with keys based on a variable. In that case traditional approach looks something like this:
Functional? Yes, and also incredibly annoying. In ES6 you can define computed property names during object declaration without having separate statements like so:
Here’s another example:
One of my personal favorite new syntax features is the shorthand assignment. Lets look at the example in ES5 first:
Sprinkle some ES6 magic and you have:
Basically, if the variable and property name is the same, you can omit the right side. Nothing stops you from mixing and matching either:
How can you take advantage of ES6 features today? Using transpilers in the last couple of years has become the norm. People and large companies no longer shy away. Babel is an ES6 to ES5 transpiler that supports all of the ES6 features.
The majority of browsers are catching up on implementing new features but not one has full support. Does that mean you have to wait? It depends. It’s a good idea to begin using the language features that will be universally available in 1-2 years so that you are comfortable with them when the time comes. On the other hand, if you feel the need for 100% control over the source code, you should stick with ES5 for now.