Lightweight ES6 Features That Pack A Punch

ECMAScript 6's "Quick Wins" that you should know.
October 10, 2014

I had been staying away from ECMAScript 6 (ES6) for quite a while now despite the offerings of advanced features and syntactic sugars by ES6. Back then, ES6 was still in the draft stage. I did not want to devote my time into some fancy features that might suddenly be yank out.

So when the feature set was frozen in Aug 2014, I decided that it was time to dive right in. Looking through the feature list, a lot of them seems really familiar. It was evident that ES6 strives to bring Javascript on par with other programming languages with the implementation of similiar features.

I grouped the feature list into two categories - The heavyweight features and the lightweight features. The heavyweight features are features like class, modules, promises, iterators, generators, etc. These features are refreshingly different and will bring major paradigm shift in terms of code structure for web developers.

Lightweight features are like "quick wins".

On the other hand, lightweight features are features that are much easier to digest but yet still bring immense amount of benefits to web developers. They are easy to use and your code structure doesn't need to undergo major face-lift. Hopefully by understanding these lightweight features, it will eventually help to ease you into ES6.

1) let keyword

It is well-known that Javascript, unlike many other programming languages, has no concept of block scope. Instead, the var keyword defines a variable that is accessible within the function scope. But with let, you are able to limit the scope of the variable to the block.

Use Case: Prevent the variable nameBlock from being changed by the if block

Live Demo: ES6Fiddle

If you are normally careful about variables and its scope, this shouldn't be a worry for you. A more practical use case will be to bind variables within the scope of the loop.

Use Case: Bind variables within the scope of the loop.

Notice that the variable i is still visible outside of the for loop. By using let in loop, you are safe from overwriting variables outside of the for loop and the variables within the loop are invisible to the outside block.

2) Destructuring Assignment

The destructuring assignment syntax allows you to extract data from array or object using a syntax that mimics the structure of the array or object literal.

Use Case: Initialize the variables firstName, lastName, totalBooks and bookType

Live Demo: ES6Fiddle

The above example demonstrates Array Destructuring and Object Destructuring. The destructuring assignment syntax looks slightly awkward at first glance. But with enough practice, you will be using it without skipping a beat.

3) Default Parameters

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.

Use Case: If parameters are undefined, set parameter seller to be "John" and price at 2

Live Demo: ES6Fiddle

Default parameters are self-explanatory. Use ES6's default function parameters if you have the need to explicitly set the default value of the parameters.

4) Rest Parameter

ES6's rest parameter syntax allows us to easily create variadic function - a function that can take in different numbers of argument. Just append the ... in front of the argument.

Use Case: Iterate over the arguments with forEach

Live Demo: ES6Fiddle

The funny thing about the arguments object is that it looks like an array and behave like an array but it is not an array. Thus, it is not able to use native Array methods such as forEach and map.

Instead you can convert it into a native array using the unsightly Array.prototype.slice.call function. Rest parameter on the other hand readily provides us with an array literal.

5) Spread Operator

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

Use Case: Replaces apply()

Live Demo: ES6Fiddle

You use apply when you want to use an array as an argument for the function. The spread operator replaces this clumsy solution.

Use Case: Create a new alphabet array that are arranged in order

Live Demo: ES6Fiddle

Instead of using splice,concat and apply, you can simply use the spread operator to flexibly arrange and form the new array.

6) Set Object

The Set object lets you store unique values of any type, whether primitive values or object references.

Use Case: Find unique values in an array

Live Demo: ES6Fiddle

To find an unique set of values in an array without the set object, you will need to filter through the collections. The filter callback checks whether the value is first occuring. If it's not, it is a duplicate value and will not be included in the tempArr. As for the set object, it will automatically include unique values only.

Note: You can directly set the array as the Set's argument with var set = new Set(arr). However, that particular method was not working on my ES6Fiddle nor Firefox's console hence I decided to use forEach to manually add the array's item into the Set. Thanks to tulchin for pointing it out.

7) Map Object

The Map object is a simple key/value map. Unlike the object literal, the object's key can be an object literal instead of a string.

Use Case: Map each DOM element with the associated content

Click on "Result" and click on the "Change box content" button

In the example above, we first setup the map object with the DOM elements and its associated content. After we click on the "Change box content" button, the box will update its content.

By setting the DOM element as a key, I still hold on to the meta data of the DOM element which I'm able to manipulate later on.

I don't see myself using this map object very often but when the situation calls for it, the map object will be an elegant solution. Credit to this article for the inspiration of the example.

Need more examples? /u/alfredwaltz came up with more in ES6Fiddle.

ES6 looks really cool! I'm so ready to use it now.

There are actually some features that you can use right now on your modern browsers such as set and map objects. You can check out the full range of ES6 supports right here.

To know what transpilers to use to compile ES6 into valid ES5 code, check out the article by 2ality. Addy Osmani also aggregated an extensive list of ES6 tools: https://github.com/addyosmani/es6-tools.

Update 13th Oct: Try esnext by Square.

When will it be ready?

According to multiple readings online, ES6 is said to be a standard by mid 2015. Anyone with official sources, please drop me an email or a tweet.

How about the heavyweight features?

The heavyweight features will be coming soon. Subscribe for updates.

RSS
http://colintoh.com/content/blog/04-lightweight-es6-features/feature.jpg