Press enter to see results or esc to cancel.

Learn ES6 in 5 Minutes Tutorial

ES6 has been around for a long time now and it quickly changed the standards of writing JavaScript. In this tutorial I’ll show you the old standards of writing JavaScript vs the new standards in ES6.

Defining Variables — Using let/const Instead of var

The “var” keyword should no longer be used to declare variables, it can been replaced with 2 new keywords. For constant values that don’t change, use “const” instead of “var”, and for values that do change use “let” instead of “var”.

Arrow Functions

Arrow functions are a shorthand way of defining functions in your code, they can also use variables outside of the current scope. Arrow functions also help to make your code more concise and readable. To use arrow functions, just omit the “function” keyword and add an arrow (=>) between the arguments and function body. To make your code even more concise you can omit the parenthesis if your function has a simple body.

Default Parameters for Functions

ES6 added default parameters to functions allowing developers to remove workaround code that was previously used to imitate this functionality. These default parameters work exactly the same as other programming languages.

Spread Operators

ES6 added spread operators which can be used to expand arrays or objects. The spread operator can be used in a method signature or on an iterable object/array.

As a Function/Method Signature

As an Iterable Object/Array

Template Literals

ES6 added template literals which provides a cleaner way to inject variables into strings. To use template literals, use the backtick character instead of quotes and wrap the variable name in dollar parentheses (${}).

Classes

This is my favourite new feature in ES6 as I come from an object oriented background. Classes allow you to design code that is truly object oriented, the syntax will look very familiar to developers from other OO languages.

The “constructor” method is called whenever this class is instantiated using the “new” keyword.

You can also use inherit from another class with the “extends” keyword. Getters and setters can be defined with the “set” and “get” keywords.

Modules and Destructuring

Using “require” was a standard way of implementing modules in JavaScript. ES6 added the new “import” and “export” keywords to implement this functionality natively.

Old Modules With Require and Module Exports

New Modules With Import/Export

One thing to note in the above example is that we are also using destructuring to extract the named export “myModule”. This means it’s possible for a module to export many variables/objects, and client code can decide which ones to use. The destructuring syntax uses parenthesis to select the exports to use.