× {{alert.msg}} Never ask again
Receive New Tutorials
GET IT FREE

4 Easy Ways to Start Using ES2015

– {{showDate(postTime)}}

ES2015

I have been writing JavaScript professionally since about 2001 — a time that seems forever ago considering how fast technology changes.

Building websites and web applications in the early 2000s was vastly different from anything we do today. Roughly 95% of the world used Internet Explorer, jQuery didn’t exist until 2006, and the “mobile web” didn’t exist until the iPhone was released in 2007. In 2009 Node.js enabled JavaScript developers to begin writing code to run on the server — and yet all of these advancements occurred utilizing variations of ECMAScript that had hardly changed since 1999.

Needless to say by the early 2010s, I considered myself an expert in JavaScript. After all, I had been building applications with JavaScript for more than 10 years!

Around 2011 or 2012 I first read about some new features being proposed for “ES6”, and I remember thinking to myself: “Browsers don’t support this stuff yet, and they won’t for a really long time. I don’t need to worry about learning it.”

Over the next few years I sat through some great presentations at conferences, watched videos on YouTube and read more articles than I can count about how ES6 (now referred to as ES2015) was becoming more standardized. Yet I remained stubborn because not every browser consistently supported these strange new features.

At some point I realized two truths:

  1. Broad support for ES2015 was coming, faster than I was prepared to admit.
  2. I was resisting ES2015 because I was scared to admit I would no longer be an expert.

With ES2015, I was scared to begin learning some of the foreign syntax I had read about. I was scared to ask questions because I didn’t want to be seen as anything less than the senior-level developer I had worked so hard to become.

But what I didn’t know was how easily I could start using ES2015 in code I had already written. I didn’t know how much more productive I would be — or just how much I would love it!

Current ES2015 Support

As I just mentioned, I resisted learning ES2015 for years because it wasn’t widely supported by the major browsers. As of this writing, the “latest” versions for Chrome, Firefox, and Microsoft Edge all support the majority of ES2015 features:

  • Chrome 52 (98%)
  • Firefox 47 (90%)
  • Microsoft Edge (79%)

Safari 9 currently has a pitiful 53%, but Safari 10 (currently in beta) has announced complete support on both OSX and iOS. And if you’re building anything in Node.js, you can enjoy 93% support using the latest Node 6 release.

Best of all, these percentages only continue to increase!

But we can’t guarantee our users will be using the latest-and-greatest browsers!

This is a valid reason to exercise some caution, and I probably would have said exactly the same thing. Fortunately, some really smart people have already solved that problem by creating Babel. Babel is a JavaScript compiler that enables you to write your code using ES2015 syntax, but ship ES5 code so that your users can still use older browsers.

The moral of this story is that you don’t have to continue making excuses to avoid ES2015. Let’s explore four easy ways you can begin using ES2015 in your code today — all without any scary learning curves!

1. Declare Variables with let and const

In traditional ES5 code, JavaScript engineers frequently lamented the limitations (and sometimes quirky behavior) of variables:

  • Lack of block-scoping
  • Lack of true constants

In ES2015, these two problems have been solved with the addition of two new keywords: let and const.

Block Scope with let

Declaring variables with let allows you to limit the usage (scope) of that variable to the block, statement, or expression on which it is used.

// in ES5
var a = 1;

if (true) {
    var b = 2;
}

console.log(a); // 1
console.log(b); // 2


// in ES2015
let a = 1;

if (true) {
    let b = 2;
}

console.log(a); // 1
console.log(b); // ReferenceError: b is not defined

Block scoping with let can be particularly useful inside loops, where we might want the true value of an iterable counter preserved:

// in ES5
var a = [];

for (var i=0; i< 5; i++) {
    a.push(function() {
        console.log(i);
    });
}

a.forEach(function(value) {
    value();
});
// output: 5, 5, 5, 5, 5


// in ES2015
var b = []; // note that “var” continues to work in ES2015

// the only difference is declaring “i” with “let”
for (let i=0; i< 5; i++) {
    b.push(function() {
        console.log(i);
    });
}

b.forEach(function(value) {
    value();
});
// output: 0, 1, 2, 3, 4

Clearly using let as a replacement for var in our code today is an easy first step towards using ES2015.

Create Constants with const

The entire point of having constants in an application is that those variables would be assigned values which could never changed — yet in ES5, JavaScript developers did not have true constants.

ES2015 allows us to declare truly constant variables using the new const keyword:

// in ES5
var MY_CONSTANT = true;
MY_CONSTANT = false; // value can be reassigned -- not truly a “constant”

// in ES2015
const MY_CONSTANT = true;
MY_CONSTANT = false; // Uncaught TypeError: Assignment to constant variable

One situation in which this might be helpful is preventing hard-to-spot syntactic bugs:

// in ES5
var MY_CONSTANT = ‘some value’;

function testValue(val) {
    // we wanted a boolean check with MY_CONSTANT === val
    // not an assignment with =
    return MY_CONSTANT = val;
}

testValue(‘123’); // “123”


// in ES2015
const MY_CONSTANT = ‘some value’;

function testValue(val) {
    // we wanted a boolean check with MY_CONSTANT === val
    // not an assignment with =
    return MY_CONSTANT = val;
}

testValue(‘123’); // Uncaught TypeError: Assignment to constant variable

The const keyword is another simple way to start using ES2015 in your applications today!

2. Template Literals

Have you ever written code that looks like this?

// in ES5

var url = ‘http://www.’ + domain + ‘.com/’ + path + ‘?’ + queryParams;

It’s not uncommon in applications to build strings that combine a number of variables together with static text — and unfortunately ES5 didn’t provide any true String.format interface for us.

With ES2015, we no longer need to rely on third-party string formatting functions because of the new template literals:

// in ES2015

let url = `http://www.${domain}.com/${path}?${queryParams}`;

Template literals are a great way to reduce the complexity of dynamic strings in your application. You can even interpolate expressions and create multi-line strings!

3. New Primitives: Set and Map

ES2015 introduced a handful of new primitives to JavaScript. And while most developers won’t need to start using them right away, there are a few cases in which it might make sense to give them a shot.

Using Set instead of Array

Every JavaScript developer has used an array to store dynamic data — they’re great for creating catch-all containers:

// in ES5
var collection = [];
collection.push(1, 2, 1);
console.log(collection); // [ 1, 2, 1]

However, there are many situations in which we might not want our collection to contain duplicate values. In those cases, we would need some conditional logic for adding items to our collection:

// in ES5
function addToCollection(collection, value) {
    if (collection.indexOf(value) < 0) {
        collection.push(value)
    }
}

ES2015 provide a new primitive called Set to help us handle these situations with greater ease:

// in ES2015
let collection = new Set();
collection.add(1);
collection.add(2);
collection.add(1);
console.log(collection); // Set {1, 2}

As you can see, our collection does not contain a duplicate entry for the number 1. The new Set primitive also gives us a variety of new methods to iterate and manipulate values within the collection.

Using Map instead of Object

Similarly, JavaScript developers are familiar with using generic Objects to store arbitrary data:

// in ES5
var thing = {};
thing.a = ‘abc’;
thing.b = ‘xyz’;

With ES2015, we have access to a new primitive — Map. A Map is simply a container for key/value pairs that solves or eliminates a few common problems for developers.

// in ES2015
let thing = new Map();
thing.set(‘a’, ‘abc’);
thing.set(‘b’, ‘xyz’);

You won’t want to use Maps in place of Objects everywhere, but they do make iterating over key/value collections much easier.

// in ES2015
let collection = new Map();
// ...add some key/value pairs with collection.set()

collection.forEach(function(value, key) {
    // you no longer need to use the hasOwnProperty() check!
});

// how many items are in the Map?
console.log(collection.size); // it’s easy to find out!

4. Function Parameters

With ES2015, working with functions and their parameters is easier than ever. Specifically, there are two new features that you can start using with a minimal learning curve:

Default Values

In traditional ES5 code, function parameters simply default to undefined when a value was not already provided.

// in ES5
function doSomething(someObject) {
    console.log(someObject);
}

If we wanted default behavior, we had to explicitly test for the presence of that value and optionally assign some default value.

// in ES5
function doSomething(someObject) {
    if (someObject === undefined) {
        someObject = {};
    }
    console.log(someObject);
}

That approach certainly isn’t horrible, but there are two obvious problems:

  1. If we forget to test against undefined, there’s a high probability of runtime errors
  2. As shown, this pattern adds three lines of code for every parameter the function accepts — code that quite honestly doesn’t add a lot of value and distracts from the actual purpose of the function

ES2015 allows us to declaratively assign default values with ease:

// in ES2015
function doSomething(someObject = {}) {
    console.log(someObject);
}

Object Destructuring

In many cases, a function may expect a parameter as an object with specific key/value properties. This is generally good practice so that the function avoids the fragility of numerous arguments — but it can also create overly-verbose and repetitive code when trying to access the properties of the object.

// in ES5
function doSomething(someObject) {
    console.log(someObject.propOne);
    console.log(someObject.propTwo);
    console.log(someObject.propThree);
}

With ES2015, we can destructure the object parameter to provide clean access to its properties:

// in ES2015
function doSomething({ propOne, propTwo, propThree }) {
    console.log(propOne);
    console.log(propTwo);
    console.log(propThree);
}

Beyond the ease of accessing the parameter’s properties, an added benefit to object destructuring is the immediate documentation it provides. In the ES5 example, it’s not clear exactly what properties the function expects its parameter to contain — but the ES2015 example makes it very clear!

Conclusion

ES2015 includes the first of what will likely be many additions and improvements to JavaScript over the next several years. Although some of these new features look foreign and scary, the reality is that they’re optional — none of our tried-and-trusted code patterns are being taken away from us. All of your existing code will continue to work, but the four ES2015 features presented in this article are really simple ways in which you can immediately begin to benefit.

I hope this article has opened the door to ES2015 for a few of you. Post some comments below and let me know if using ES2015 has made you feel more productive!


Learn more about ES6:

 



Author
Arthur Kay
Arthur Kay
Technology Leader || Software Architect
Arthur Kay has been working with the Web since the late 1990s, when GeoCities and scrolling marquees were all the rage. Since those early days, Arthur graduated from Loyola University Chicago...
Hire the Author

Questions about this tutorial?  Get Live 1:1 help from JavaScript experts!
Warith Omoyele
Warith Omoyele
5.0
<Senior Software Engineer, Server Administrator/>
With years of experience in finance, web3, and education, i specialize in developing cloud-based applications. I've led key roles in large...
Hire this Expert
Olajide Olanrewaju
Olajide Olanrewaju
5.0
Multi-talented Full Stack Developer & Web Security Researcher also Robotic Engineer
I am a **Multi-talented** professional adept in **Full Stack Web Development**, **Web Security Research**, and **Robotics Engineering**. As a...
Hire this Expert
comments powered by Disqus