ECMAScript6 (also referred to as ECMAScript2015) is the most recent recent ECMAScript with a finalized specification. ES6 was a major update to ES5 and introduces many new features to JavaScript.
In this article, we'll walk through how to set things up to develop ES6 applications and get started with some of the most important new features.
It is important to note that ECMAScript7, is currently in development and should be finalized sometime this year (2016). ES7 and other future versions are planned to be smaller updates that will be released on an annual schedule.
The set-up required for developing ES6 apps depends on the level support you want to provide across different runtimes. The newest versions of Chrome, Firefox, Edge, and Node.js already support most of ES6, so if you're only targeting these newer runtimes then you can start using ES6 immediately. For further details about which runtimes support which features, you can consult the ES6 compatibility table.
You can run the following code in your browser's JavaScript console. If your browser supports ES6, it should evaluate to 3
. If not, it will complain about a syntax error.
1let [one, two] = [1, 2];
2one + two;
Unfortunately, the overall browser market may not be up to date, which means that many people still don't use a browser that supports ES6. You should still support these people if you're building a web application that you plan to release to the public.
Fortunately, there's a project called Babel which allows you to convert your ES6 code into ES5 code. This means that you can still write code in ES6 while developing web applications that anybody with an ES5-compliant browser can use. It takes some effort to figure out how to set everything up the first time, so I've included a step-by-step guide below to help you get started more quickly.
If you do not already have Node.js installed, you will need to install it.
Create a folder for your project, then create a file named package.json
with the following content:
1{
2 "name": "es6-demo",
3 "scripts": {
4 "build": "webpack --watch"
5 },
6 "devDependencies": {
7 "babel-cli": "^6.8.0",
8 "babel-core": "^6.8.0",
9 "babel-loader": "^6.2.4",
10 "babel-plugin-transform-runtime": "^6.8.0",
11 "babel-preset-es2015": "^6.6.0",
12 "babel-runtime": "^6.6.1",
13 "webpack": "^1.13.0"
14 }
15}
Then create a file named webpack.config.js
with the following content:
1var path = require("path");
2module.exports = {
3 entry: "./src/main.js",
4 output: {
5 path: __dirname,
6 filename: "bundle.js"
7 },
8 module: {
9 loaders: [
10 {
11 loader: "babel-loader",
12
13 // Compile files in /src directory
14 include: [path.resolve(__dirname, "src")],
15
16 // Babel options
17 query: {
18 plugins: ["transform-runtime"],
19 presets: ["es2015"]
20 }
21 }
22 ]
23 }
24};
Then create a subfolder named src
. This folder will contain all of your ES6 code. Let's put a simple script there named main.js
just to test things out.
1let [one, two, three] = [1, 2, 3];
2console.log(`One: ${one}, Two: ${two}, Three: ${three}`);
Open your terminal (Node.js console for Windows users), navigate to your project folder, and run the following:
1npm install
2npm run build
This will create a bundle.js
file in your project folder with the compiled ES5 code. If you open this file, you'll see the ES5 equivalent (in the middle of a bunch of other generated boilerplate):
1var one = 1;
2var two = 2;
3var three = 3;
4
5console.log("One: " + one + ", Two: " + two + ", Three: " + three);
The npm run build
script is set up to listen for modifications in the src
folder. Now, when you modify the main.js
file, the bundle.js
file will update automatically. You can stop watching with Ctrl
+ C
in the console.
After you've done this, there's no need to run npm install
again. When you need to convert your code, you can use npm run build
.
For a better development experience, you also will probably want to use a code editor that has some ES6 tooling. I like to use Visual Studio Code, but there are many editors that can be set up to support ES6, such as vim, Atom, Sublime Text, and WebStorm.
In my opinion, the module is the single most important new feature in ES6. It allows you to separate your code into separate files in a modular way without worrying about cluttering the global namespace.
For example, let's create a file math.js
with a toy math library that exports the value of pi and a couple of pi-related functions:
1export const PI = 3.141592653589793;
2export function circumference(r) {
3 return 2 * PI * r;
4}
5export function area(r) {
6 return PI * r * r;
7}
With modules, we can import this library's individual components from another file:
1import { PI, area } from "./math";
2console.log(area(PI));
Or we can import everything into a single object:
1import * as math from "./math";
2console.log(math.area(math.PI));
You can also export a single value as the default value, so that you can import it without needing brackets or a wildcard:
1// reverseString.js
2export default function(str) {
3 return str
4 .split("")
5 .reverse()
6 .join("");
7}
8// main.js
9import reverseString from "./reverseString";
10console.log(reverseString("Hello, world!"));
const
is used for constant declarations, and let
is used for variable declarations.
If you try to reassign to a constant, the compiler will throw an error:
1const one = 1;
2one = 2; // SyntaxError: "one" is read-only
let
is similar to var
, but it fixes a number of quirks about var
that are often stumbling blocks to JavaScript newcomers. In fact, var
has become obsolete at this point because it's let
and const
have assumed its functionality.
let
is block-scopedvar
and let
differ in their scoping mechanisms. A variable declared with var
is function-scoped, which means that it is visible anywhere in the surrounding function. Meanwhile, a variable declared with let
is block-scoped, which means it is only visible in its own code block. Calls to the variable outside its code block will lead to errors.
1// var
2console.log(less); // undefined
3if (1 < 2) {
4 var less = true;
5 console.log(less); // true
6}
7console.log(less); // true
8
9// let
10console.log(less); // Uncaught ReferenceError: less is not defined
11if (1 < 2) {
12 let less = true;
13 console.log(less); // true
14}
15console.log(less); // Uncaught ReferenceError: less is not defined
const
also exhibits this block scoping strategy.
let
declarations are forbiddenlet
is designed to catch potential assignment mistakes. While duplicate var
declarations will behave like normal reassignment, duplicate let
declarations are not allowed to prevent the common mistake of erroneous reassignment.
1var x = 1;
2var x = 2; // x equals 2
3
4let x = 1;
5let x = 2; // SyntaxError: Identifier 'x' has already been declared
let
variables rebound in each loop iterationHere is a common error that occurs when you have a function defined inside of a loop using var
.
1for (var i = 0; i < 5; i++) {
2 setTimeout(function() {
3 console.log(i);
4 }, 10);
5}
6// logs 5 5 5 5 5
This code will log the number 5 five times in a row, because the value of i
will be 5
before the first time console.log
is called. When we use let
instead, the i
inside of the function will correspond to the value on that particular iteration of the for-loop.
1for (let i = 0; i < 5; i++) {
2 setTimeout(() => {
3 console.log(i);
4 }, 10);
5}
6// logs 0 1 2 3 4
Object-oriented programming in JavaScript is different than classical OOP because it uses prototypes rather than classes. ES6 classes are a syntax shortcut for a common JavaScript pattern used to simulate classes. Below, I lay out prototype creation in ES5 and class creation in ES6.
1// ES5 way
2function Circle(x, y, radius) {
3 this.x = x;
4 this.y = y;
5 this.radius = radius;
6}
7Circle.prototype.move = function(x, y) {
8 this.x = x;
9 this.y = y;
10};
11Circle.prototype.area = function() {
12 return Math.PI * Math.pow(this.radius, 2);
13};
14
15// ES6 way
16class Circle {
17 constructor(x, y, radius) {
18 [this.x, this.y, this.radius] = [x, y, radius];
19 }
20 move(x, y) {
21 [this.x, this.y] = [x, y];
22 }
23 area() {
24 return Math.PI * Math.pow(this.radius, 2);
25 }
26}
You can also extend classes in a manner consistent to standard object-oriented languages:
1// ES5 way
2function ColoredCircle(x, y, radius, color) {
3 Circle.call(this, x, y, radius);
4 this.color = color;
5}
6ColoredCircle.prototype = Object.create(Circle.prototype);
7
8// ES6 way
9class ColoredCircle extends Circle {
10 constructor(x, y, radius, color) {
11 super(x, y, radius);
12 this.color = color;
13 }
14}
It's common to create objects with property names matching variable names. ES6 includes new syntax to make this a little bit more concise:
1var x = 5,
2 y = 6;
3
4// ES5 way
5var coordinate = { x: x, y: y };
6
7// ES6 way
8let coordinate = { x, y };
The syntax for function properties has also changed:
1// ES5 way
2var counter = {
3 count: 0,
4 increment: function() {
5 this.count++;
6 }
7};
8
9// ES6 way
10let counter = {
11 count: 0,
12 increment() {
13 this.count++;
14 }
15};
Destructuring assignment is a nifty feature for doing several assignments at once. In ES5, you often have a series of variable declarations like this:
1var a = 1,
2 b = 2,
3 c = 3;
In ES6 you can do it all at once with array destructuring:
1let [a, b, c] = [1, 2, 3];
This is particularly nice for extracting values from an array:
1var personData = ["John", 12, true];
2
3// ES5 way
4var name = personData[0],
5 age = personData[1],
6 isMale = personData[2];
7
8// ES6 way
9let [name, age, isMale] = personData;
and also for swapping variables:
1// ES5 way
2var tmp = a;
3a = b;
4b = tmp;
5
6// ES6 way
7[a, b] = [b, a];
Destructuring assignment can be used with objects as well:
1var personData = {
2 name: "John",
3 age: 12,
4 isMale: true
5};
6
7// ES5 way
8var name = personData.name,
9 age = personData.age,
10 isMale: personData.isMale;
11
12// ES6 way
13let { name, age, isMale } = personData;
This also works with nested object structures:
1var book = {
2 title: "A Tale of Two Cities",
3 dimensions: [12, 8, 3],
4 author: {
5 name: "Charles Dickens"
6 }
7};
8
9// ES5 way
10var title = book.title,
11 length = book.dimensions[0],
12 width = book.dimensions[1],
13 depth = book.dimensions[2],
14 name = book.author.name;
15
16// ES6 way
17let { title, dimensions: [length, width, depth], author: { name } } = book;
Clear and concise.
JavaScript developers frequently use function expressions, such as callbacks. However, code can often look messy when the keywords function
and return
are repeated many times. ES6 has new syntax to make function expressions less verbose.
Let's compare ES6 function expression handling with expression handling in previous Ecmascript versions.
1var list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2
3// ES3 way
4var sumOfSquares = 0;
5for (var i = 0; i < list.length; i++) {
6 var n = list[i],
7 square = n * n;
8 sumOfSquares += square;
9}
10
11// ES5 way
12var sumOfSquares = list
13 .map(function(x) {
14 return x * x;
15 })
16 .reduce(function(a, b) {
17 return a + b;
18 });
19
20// ES6 way
21let sumOfSquares = list.map(x => x * x).reduce((a, b) => a + b);
For functions consisting of more than one statement, you can wrap the right-hand side of the arrow function in curly braces:
1// ES5 way
2window.onclick = function(e) {
3 if (e.ctrlKey) console.log("Ctrl click");
4 else console.log("Normal click");
5};
6
7// ES6 way
8window.onclick = e => {
9 if (e.ctrlKey) console.log("Ctrl click");
10 else console.log("Normal click");
11};
There is a new type of string literal that makes it easier to insert dynamic values into strings, and also to deal with multi-line strings. Instead of double quotes or single quotes, template strings are delimited by backticks.
1var weight = 80,
2 height = 1.8;
3
4// ES5 way
5console.log("You are " + height + "m tall and weigh " + weight + "kg.\n" +
6"Your BMI is " + weight / (height * height) + ".");
7
8// ES6 way
9console.log(`You are ${height}m tall and weigh ${weight}kg.
10Your BMI is ${weight / (height * height)}.`);
I've tried to cover some of the most important new changes, but there are many other cool new features in ES6 that I don't have space to cover in this article. For more information, you can browse a quick overview of the new features on es6-features.org, read a more detailed introduction in the Exploring ES6 book, and, for even more in-depth details, read the ECMAScript 2015 Language Specification.
I've created a simple example project that you can play around with to get acquainted with ES6. It is an implementation of the snake game in both ECMAScript5 and ECMAScript6.
You can play this snake game online. My high score is 71, try to see if you can beat it. :)
Instructions for downloading the source code and setting things up can be found on the GitHub repository for this project.
To get your feet wet with ES6, I suggest downloading this project, making sure that you can set everything up, and then play around with the code. In the src
folder, there is a script called options.js
that has a number of settings you can tinker around with and see how they change the game.
If you don't have any ideas about what to try, I would suggest things like changing the color of the snake, changing the speed of the snake, making the snake grow faster, and making the game larger or smaller. These can all be achieved just by modifying the options script.
If you want to try your hand at a more challenging task, here are some ideas:
One annoying thing about having to compile your code to run on the browser is that the code you write and the code you see while debugging are different. This can make debugging an even more frustrating task than it already is.
A common solution for this issue is source maps. Source maps essentially keep track of the relationships between parts of the compiled code correspond and parts of the original code. If you have a browser that supports source maps (most common commercial browsers will do this), you can create break points and debug with your original code, even though the compiled code is actually what is being executed.
Fortunately, webpack makes this easy to set up. In the webpack.config.js
file, insert this line into the module.exports
object:
1devtool: "source-map",
Now when you run npm run build
, it should generate a bundle.js.map
file alongside the bundle.js
script. If you use Chrome or Firefox to debug the script, they should be able to automatically detect the source map file. If not, check your source maps settings in the developer console. For example, in Google Chrome, there's an "Enable JavaScript source maps" checkbox:
Minification is a process designed to reduce the size of files that the browser has to download (including HTML, CSS, and JavaScript files). The goal is to minimize the amount of time the user has to wait for resources to downloaded. JavaScript minifiers achieve this by stripping out comments, unnecessary white space, renaming variables to make them shorter, and so forth.
Minification makes the file size smaller, but it also makes the script more difficult for humans to read. That said, since we already have source maps set up, we don't need to read the compiled output for debugging, so we might as well minify our code as well.
Webpack has a "production mode" option that includes script minification. To enable it, just add a -p
flag to the build script in the package.json
file:
1"scripts": {
2 "build": "webpack --watch -p"
3},
If you downloaded the example snake game code in the last section, you can try this out by opening the ES6Snake.html
file. In Chrome, if you open up the developer console and open up the bundle.js
file, it will show a message about it being minified and having source maps associated with it:
You can open up the original scripts in the file tree under the webpack://
node:
Then you can open one of these scripts, place breakpoints, and debug just like you normally would.
Linters are tools that analyze your code and look for compile-time mistakes, such as assigning a variable to itself, using =
instead of ==
, and so forth. If you put your ES6 code through a normal JavaScript linter designed for ES5, it will most likely complain about syntax errors because it doesn't recognize the new features.
ESLint is a popular linting tool for JavaScript, and you can configure it to support ES6. To install it, run
1npm install eslint --save-dev
Then create a file named .eslintrc.json
in your project folder with the following content:
1{
2 "parserOptions": {
3 "ecmaVersion": 6,
4 "sourceType": "module"
5 },
6 "env": {
7 "browser": true
8 },
9 "extends": "eslint:recommended"
10}
Then in your package.json
file you can add a script for linting:
1"scripts": {
2 "build": "webpack --watch -p",
3 "lint": "eslint src/*"
4},
Now you can run ESLint with the following command:
1npm run lint
If there are any mistakes it catches, it will print them into the console. Otherwise, the linter will not print anything.
If you've followed along up to here, then you should be familiar enough with ES6 and the tools used to develop with ES6 to begin experimenting with the language specification in your own projects.
For more details about ECMAScript 6, you can browse through es6-features.org, read the Exploring ES6 book, or even read the ECMAScript 2015 Language Specification.
ES7 is coming out soon, and Babel can already be configured to support some ES7 features. You can read more about upcoming features proposed for the next version of ECMAScript on the official repository for ECMA262 proposals.
For more information about the various tools used in this article, you can consult the Babel website, the webpack website, and the ESLint website.
Feel free to suggest edits to this article or to open issues or pull requests on the snake game repository. Thank you for reading. I hope you enjoyed this tutorial on ES6 features and development.