An Overview Of Common ECMAScript 6 (ES6) Syntax & Features

Note: This is part 1 of three-part series An Overview of ECMAScript 6 (ES6) Syntax & Features series.. This learning post is still in active development and updated regularly.

ECMAScript 2015, also known as ECMAScript 6 (ES6), has significant updates in JavaScript (JS) syntax and added new features. This update is considered to be a huge and many books, tutorials and learning posts are written on ES 6. Luke Hoban‘s list of ES6 features and ES6 Cheat Sheet by Jorge Cuadra (vasco3) provide summary of ES6 features.

Modern JS is also known as ES6 and its features are heavily used in JS frameworks like React, VueJs, Angular etc. In this learning-note series, following key ES6 features are discussed.

Article Series
Part 1: Basic Syntax (this post)
Part 2: Functions, Objects & Classes
Part 3: Asynchronous Features

The definition used in the following section is directly lifted from the MDN documents here. They should be considered as quote.

Basic ES6 Syntax

1. Let & Const

The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let" target="_blank" rel="noopener">let</a> statement declares a block scope local variable, optionally initializing it to a value. The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const" target="_blank" rel="noopener">const</a> similar to the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let" target="_blank" rel="noopener">let</a> statement except that value of const can’t be reassigned and redeclared.

Differences between var, let and const

Revising Tania Rascia‘s comparative var, let and const table based on scope, hoisting and reassignment.

Keyword Scope Hoisting Can Be Reassigned Can Be Redeclared
var Function scope Yes Yes Yes
let Block scope No Yes No
const Block scope No No No
Basic Syntax
// declaration with let
let var1 = value1;

// declaration with const
constvar1 = value1
Use Case Example
// ES5
//Variables holding different data type
var car = "Toyota";  // strings
var year = 2018; //numbers
var model = [ "Corolla", "Camry", "RAV4" ]; // arrays
var color = { corolla: "red", camry: "blue" }; //objects
var success = true; //Boolean
var nothing = null; // nothing or null

//ES6
let car = "Toyota";  // strings
let year = 2018; //numbers
let model = [ "Corolla", "Camry", "RAV4" ]; // arrays
let color = { corolla: "red", camry: "blue" }; //objects
let success = true; //Boolean
let nothing = null; // nothing or null

const car = "Toyota";  // strings
const year = 2018; //numbers
const model = [ "Corolla", "Camry", "RAV4" ]; // arrays
const color = { corolla: "red", camry: "blue" }; //objects
const success = true; //Boolean
const nothing = null; // nothing or null

This topic is discussed in detail in a separate post Declaring JS Variables – var, let & const in more detail.

Additional Information: Declarations | MDN JS Guide

2. Template Strings

To quote MDN, “template literals are string literals allowing embedded expressions“. They are ES6 added features which allows to a placeholder. Before ES6, a string can be defined with single quote '  ' or double quote "  " .

Syntax
// basic syntax from 
`string text`
// multilines 
`string text line 1
 string text line 2`
// expression
`string text ${expression} string text`
Example
//ES5
let subject = "ReactJs";
let topic = 'Components';

//ES6
let subject = `ReactJs`;
let topic = `Components`;

//embedding expression
`The ${subject} is all about ${topic}.`;
//OUTPUT
 The ReactJs is all about Components.

String concatenation with template literals in ES6 much cleaner & easier.

//contenation 
const version = 16.7; 

//ES5 const 
const string= 'Current React version is ' + version+'.';
//OUTPUT
Current React version is 16.7.
//ES6 
const string= `Current React version is ${version}.`; 
//OUTPUT
Current React version is: 16.7.

Additional Information: Template literals (Template strings) | MDN Web Docs

3. Map

The Map is an object which hold key:value pairs in the order of original insertion. Unlike in an object (which hold only strings and symbols), the keys in Map can be any value including functions, objects and any primitive value.

Syntax
// basic syntax
new Map([iterable])

The iterable are array with key-value pair elements.

Creating Map
//simple map
const myTopics= new Map([ [1, 'JS'], [2, 'WP'], [3,'ReactJs'] ]); 

// iteration with for..of loop
for (const [key, value] of myTopics) {
  console.log(key + ' = ' + value);
}

//OUTPUT
1 => "JS"
2 => "WP"
3 => "ReactJs"

This section is discussed in more detail in separate posts (i)  Learning JavaScript Maps & Sets, and (ii) Understanding JavaScript WeakMaps & WeakSets.

Addition Information: Map | MDN Web Docs

4. Sets

The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set" target="_blank" rel="noopener">Set</a> object lets you store unique values of any type, whether primitive values or object references.  The sets can be iterated in their order of insertion.

Syntax
// basic syntax
new Set([iterable]);

The iterable are array with key-value pair elements.

Creating Set
// create Set
const mySet = new Set([1, 2, 3, 5]);

The Set object logs the unique elements in their order of insertion.

//create sets
const mySet2 = new Set([10, 20, 30, 30, 40, 40]); 
console.log(mySet2);

//OUTPUT 
[10, 20, 30, 40] //unique

The Set object can be iterated over using for..of loop.

//iterating over Set2
for (const value of mySet2) {
  console.log(value);
}
//OUTPUT
10
20
30
40

This section is discussed in more detail in separate posts (i)  Learning JavaScript Maps & Sets, and (ii) Understanding JavaScript WeakMaps & WeakSets.

Additional Information: Set | MDN Web Docs

5. Spread Operators

The Spread syntax is used expand an array and thy are represented by ( ... ) three dots.

Basic Syntax
//function call
myFunction(...iterableObj);

//array literals or strings
[...iterableObj, '4', 'five', 6];

// object literals (ECMAScript 2018)
let objClone = { ...obj };
Sample Use Cases

Spread syntax can be used to copy an array.

// expanding an array
const topics = ['WordPress', 'Gutenberg', 'PHP']
const moreTopics = [...topics, 'ReactJs', 'Vue']
console.log(moreTopics)

//OUTPUT
 ["WordPress", "Gutenberg", "PHP", "ReactJs", "Vue"]
The spread operators can also be used two concat (or expand) two or more arrays.
// concat arrays
const topics1 = ['WordPress', 'Gutenberg', 'PHP']
const topics2 = ['ReactJs', 'Vue']
const concatTopics = [...topics1, ...topics2];
console.log(concatTopics); 
//OUTPUT
[ "WordPress", "Gutenberg", "PHP","ReactJs", "Vue"]

The Spread syntax can also be used in function calls.

// spread in function calls
const myArray = [2, 4, 6];
const myFunc = (x, y, z) => x * y * z;
//OUTPUT
console.log(myFunc(...myArray)); // 48

Additional Information: Spread syntax | MDN Web Docs

6. Rest Parameters

The rest parameter syntax allows us to represent an indefinite number of arguments as an array.

Syntax
// basic syntax
function myFunction(a, b, ...theArgs) {
  // code block here
}
Use Case Examples

In the example below, the a and b arguments (line 6) are mapped to expected 1st and 2nd passed arguments in functional call (line 12) but the third argument theRest (line 6) will map to the 3rd, 4th, .. nth (or as many) arguments.

//define function with Rest arguments
function myTopics(a, b, ...theRest) {
    console.log(a)  // JS
    console.log(b)  // PHP
    console.log(theRest) // [10, 15, 25]
}
//function call & passing argument 
myTopics('JS', 'PHP', 10, 15, 25 )

Additional Information: Rest parameters | MDN Web Docs

7. For of Loops

The for..of statement creates loop over iterable objects.

Basic Syntax
// basic syntax
for (variable of iterable) {
  // statement
}
Example

The for..of statement can be used to iterate over an array.

//iteration over an array
const topics = ['JS', 'WordPress', 'ReactJs', 'Gutenberg', 'Vue']
for (let topic of topics) {
    console.log(topic)
}
//OUTPUT
JS
WordPress
ReactJs
Gutenberg
Vue

This topic is discussed in detail under the'for..of'Statement in Understanding JavaScript For Loops post.

Additional Information: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of" target="_blank" rel="noopener">For..of</a> Statement | MDN Web Docs

7. Modules – Export & Import

In JavaScript functions, objects or values can be shared between programs with import and export statements. JS modules are nothing but files with normal JS codes. They perform in strict mode "use strict"; even if not specified.

An Example

Using modules in HTML file. A module can be imported using <script> element embeds and module can be added to the <script type="module"> as shown below (line 6).

<!DOCTYPE html>
<html>
   <head>
     <title>Importing module</title>
        <script src="asset/util.js"></script>
        <script type="module" src="asset/main.js"></script>
    </head>
    <body>
    </body>
</html>

In the example above, the utli.js is an export file where as main.js is an import file in a folder named asset.

Export Statement

Br default, any code inside a module is localThe <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export" target="_blank" rel="noopener">export</a> statement is used to make  any declaration or values in modules public so that other programs can use them with the import statement. The basic export statement syntax as described in MDN documents.

Basic Syntax
//named exports
export { myFun }; // exports a function declared earlier
export function FunctionName() {..}
export const var1 = name1, .., ..nameN; // exports a constant
export class ClassName {..}

//default function/class export
export default function() {}
export default function funcName() {..}
export default class {}

Any top-level function, class, var, let, or const can be exported.

Use Case Examples

Lets say, we have a simple util.js file in a asset folder. The entire file can be exported with a single export statement as shown below.

//export asset/util.js
const hello = "Hello, World"; // a constant
const anArray = [2, 4, 6]; //an array
const anObject = {1, 3, 5}; //an object
// a function
function greeting() {
    return "Hello, World!";
}
// with single export statement
export { hello, anArray, anObject, greeting }

It can also be exported with export statement for each function, var, class, etc. as shown below.

// Named export - asset/util.js
export function welcome() {
    return "Hello, World!";
}

An entire module can also be exported as export default file as shown below.

//default Export - asset/util.js
const helloWorld = {
    hello: function() {
        return "Hello";
    },
    world: function() {
        return "World";
    }
}
export default helloWorld;

Additional Information: Export | MDN Web Docs

Import statement

The <strong>import</strong> statement is used to import bindings that are exported by another module. The basic import syntax as described in the MDN Documents.

Basic Syntax
//import entire module
import * as name from '/asset/module-name.js';
//import a single export from a assets
import { export } from '/asset/my-module.js';
// import multiple exports from assets
import {foo, bar} from '/asset/my-module.js';
//import an export as different name
import {expert as alias} from '/asset/my-module.js';
// import default
import defaultExport from '/asset/my-module.js';
Use Case Examples

In this section, the modules exported in the previous section with export statement are imported  in asset/main.js file.

Import a single export from a module. In the example below only single item anObject (line 10) exported in previous section is imported.

// import a single item asset/main.js
import { anObject } from '/asset/util.js';

Import multiple exports from a module. In the example below only two items hello and anArray (line 10) exported in previous section are imported.

//multiple items import to asset/main.js
import {hello, anArray} from '/asset/util.js';

An export can be imported with different name (alias). In the following example const hello (line 10) from previous export section is imported as myString alias.

// import item with different names to asset/main.js
import { hello as myString } from '/asset/util.js';

Import a named export. In the following example welcome function is imported from named export (lines: 12-14) from previous section.

//named function import to asset/main.js
import welcome from '/asset/util.js';

Importing defaults.  A default export (function, object, class, var, etc.) can be imported with default import syntax (line 10) with namespace (line 13)  or specific named (line 16) from asset/util.js files from export section (lines: 15-24).

//direct import to asset/main.js
import helloWorld from '/asset/util.js';

// as namespace to asset/main.js
import helloWorld, * as util from '/asset/util.js

// as named imports to asset/main.js
import helloWorld, {hello, world} from '/asset/util.js';

Additional Information: Import | MDN Web Docs

Wrapping Up

In this learning-note post series, an overview of ES6 basic features & syntax introduced in declaring variables, template strings, map, set, spread & rest parameters, and for..of loops are presented.Links to detail discussion on these topics and/or additional resources are provided at end of each topic.

Part 2: ES6 Features – Functions, Objects & Classes

Useful Resources and Links

While preparing this post, I have referred the following references extensively. Please to refer original posts for more detailed information.