Integration and Comparison for ES6

If you’re still writing JavaScript using ES5 (also known as ECMAScript 5) and desire to author in ES6 (ES2015) fear not. We’ll look over some logical ways to start using this new syntactical sugar in your own work starting immediately. We’ll discuss and examine approaches to integrate features such as let and const plus compare var versus let and finally understand when to use the spread operator. So without further ado let’s get started.


A Brief Review

For those that have never written in ES6 please keep reading otherwise feel free to skip over this portion and begin with the next section covering terminology. For those sticking around it’s time for a quick review on how to author ECMAScript 2015.

In order to author in ES6 as of this writing you’ll need a tool known to developers as Babel; a JavaScript compiler. This is just a fancy tool that consumes the originally authored code and rewrites it into code the browser understands. You can read the other part of this series on this very website where I share helpful advice on Preparing for ES6.


Terminology

It wouldn’t be prudent if we didn’t go over some terminology before we begin so let’s learn a few definitions to help us better understand.

let

In ES2015 let is the new var and what’s known as a block-scoped binding construct. The keyword let as well as const are also both part of the “Declarations and the Variable Statement” section of the specification

The let statement declares a local block scope variable, optionally initializing it to a value. It allows for declaring variables that are limited in scope to the block, statement, or expression used within. This is unlike the var keyword that defines a variable globally or locally to an entire function regardless of block scope. It can also signal that the variable may be reassigned in cases such as a loop counter, or a value switch in an algorithm.

const

The keyword const states the identifier can’t be reassigned unlike how let and var allow for. This keyword is single-assignment whereas let can be defined multiple times. Those familiar authoring in PHP will already understand this type of identifier. A const object can have properties mutated and signals that the identifier won’t be reassigned. Static restrictions for const prevent use before assignment.

The spread operator (…)

The spread operator is a way to pass multiple arguments instead of single values as we’ve typically been used to. This allows an expression to be expanded in places where multiple arguments for functions or multiple elements (for array literals) or multiple variables (for destructuring assignment) are expected (source: MDN).


Examples

Now that you’re up to speed it’s time to use ES2015, but how do we know when using let vs var is sensible and when it’s appropriate? How should we decide when to use const or the spread operator?

How to use let

Use let when you need to reassign a variable or protect the use of a value in a blocked scope. A use case for let tends to be for loops or mathematical algorithms. The keyword let also signals that the variable will be used only in the block it’s defined in; no hoisting. If you need to reassign let make sure not to use the let keyword and use the assignment already given. For example…

Incorrect


let window_width = window.innerWidth;
let window_width = 'string';

Correct


let window_width = window.innerWidth;
window_width = 'string';

The keyword let can also be used within a functions block scope.


function windowSize() {
  let window_width = window.innerWidth;
}

windowSize();

window.onresize = function() {
  windowSize();
};

console.log(window_width) // reports undefined

In the example we define window_width only within the scope it’s used in order to determine window width on the window resize event. Keep in mind window_width is never accessible outside the windowSize function.

How to use const

Constants are block-scoped, much like variables defined using the let keyword. The value of a constant cannot change through re-assignment, and it can’t be redeclared. Think of “constant” as meaning a “one-time assignment.”


const window_width = window.innerWidth;

If we try to reassign the identifier we’ll get a warning in the console:


const window_width = window.screen.width;
window_width = 'string'; // Uncaught TypeError: Assignment to constant variable.

You’ll likely use a constant when a value is unlikely to change throughout your application in such cases like mathematical values.


const pi = Math.PI;

Here we’ve created a read-only reference meaning we can only read the value not reassign it as previously stated.

We can get around the immutable rule by defining our values within an object literal. Global configurations are a great use case for const when used in the following fashion:


const config = {
    url: window.location.origin,
    width: window.screen.width,
    path: window.location.pathname
};

// The object's properties can be mutated so we can reassign values.
config.url = "https://codepen.io";

console.log(config)

Object {url: "https://codepen.io", width: 1440, path: "/index.html"} // url key reports reassigned value

Here we’ve created a read-only reference meaning we can only read the value (config) not reassign it as previously stated. Essentially the config identifier is the constant being defined and cannot be overridden, but we still have the ability to mutate properties contained within as shown.

How to use (…) : the spread operator

The spread operator adds more capability to the once dull context of accepted arguments we’ve previously encountered in ES5. Spread operators can accept an array of arguments; for example:


function spreadReporter(...values) {
  let object = [...values];
  return object[0].length;
}

var items = ['one', 'two', 'three'];

console.log(spreadReporter(items)); // reports the numerical value 3

These arguments consisting of multiple values can be anything you desire. It can be an identifier with values using an object literal or an array of values.

You could use the spread operator in a e-commerce situation based on events such as adding items to a category or shopping cart.


let dairy = [];
let store = {
  add: function(category, ...items) {
    category.push(...items);
  }
};

store.add(dairy, 'milk', 'sour cream');
store.add(dairy, 'ice cream', 'yogurt', 'cheese');
console.log(dairy);

// outputs ["milk", "sour cream", "ice cream", "yogurt", "cheese"]

Events could also be a great use case to determine the particular type taking place whether it be a click, touch or some other type of gesture variant. I’ll leave that up to you all as a challenge so feel free to post a solution in the comments below.


Conclusion

As with everything in development there can be many ways to skin a cat. These examples provided for discussion are merely suggestions and demos showcasing the power of the new features in ES6. If you have any other samples, suggestions that outline the features mentioned above please let us know in the comments. Happy coding everyone and enjoy your new ES6 knowledge. Go forth, share, discuss and be awesome.

References

Want to become a better web developer?

Join over 25,000 other developer & designers who get awesome links to the best news and articles each week delivered directly to their inbox.

Dennis Gaebel

Design Technologist passionate for Open Source, SVG, Typography, Web Animation, Interaction Development & Pattern Based Design. http://droidpinkman.io.

This post currently has no responses. What do you think?

You can use basic HTML when posting code, please turn all < characters into &lt; or > into &gt;
If the code is multi-line, use <pre><code></code></pre>

Leave a Reply

Your email address will not be published. Required fields are marked *