Easy Tutorial
❮ Python Docstrings Insertion Sort ❯

ECMAScript 6 Concise Tutorial

Category Programming Techniques

ECMAScript 6 has essentially become the industry standard, and its adoption rate is much faster than that of ES5, mainly because modern browsers have been very quick to support ES6, especially Chrome and Firefox, which already support the vast majority of features in ES6.


1. let, const, and Block Scope

let allows the creation of block-level scope. ES6 recommends using let to define variables within functions instead of var:

var a = 2;
{
  let a = 3;
  console.log(a); // 3
}
console.log(a); // 2

Another variable declaration method that is also effective within block scope is const, which can declare a constant. In ES6, constants declared with const are similar to pointers, meaning they point to a reference, which means this 'constant' is not immutable, for example:

{
  const ARR = [5,6];
  ARR.push(7);
  console.log(ARR); // [5,6,7]
  ARR = 10; // TypeError
}

There are a few points to note:

2. Arrow Functions (Arrow Functions)

In ES6, arrow functions are a shorthand form of a function, using parentheses to wrap the parameters, followed by a =>, and then the function body:

var getPrice = function() {
  return 4.55;
};

// Implementation with Arrow Function
var getPrice = () => 4.55;

It should be noted that the above example of the getPrice arrow function uses a concise function body, which does not require a return statement. The following example uses a normal function body:

let arr = ['apple', 'banana', 'orange'];

let breakfast = arr.map(fruit => {
  return fruit + 's';
});

console.log(breakfast); // apples bananas oranges

Of course, arrow functions are not just for making the code more concise, but also because the this within the function is always bound to the object itself. For specifics, you can see the following examples:

function Person() {
  this.age = 0;

  setInterval(function growUp() {
    // In non-strict mode, the this of the growUp() function points to the window object
    this.age++;
  }, 1000);
}
var person = new Person();

We often need to use a variable to save this, and then refer to it in the growUp function:

function Person() {
  var self = this;
  self.age = 0;

  setInterval(function growUp() {
    self.age++;
  }, 1000);
}

However, using an arrow function can save this trouble:

function Person(){
  this.age = 0;

  setInterval(() => {
    // |this| points to the person object
    this.age++;
  }, 1000);
}

var person = new Person();

3. Default Function Parameters

In ES6, you are allowed to set default values for function parameters:

let getFinalPrice = (price, tax=0.7) => price + price * tax;
getFinalPrice(500); // 850

4. Spread / Rest Operator

The Spread / Rest operator refers to ..., whether it is a Spread or Rest depends on the context.

When used in an iterator, it is a Spread operator:

function foo(x,y,z) {
  console.log(x,y,z);
}

let arr = [1,2,3];
foo(...arr); // 1 2 3

When used in function arguments, it is a Rest operator:

function foo(...args) {
  console.log(args);
}
foo( 1, 2, 3, 4, 5); // [1, 2, 3, 4, 5]

5. Object Lexical Extensions

ES6 allows the use of shorthand syntax when declaring in object literals, to initialize property variables and function definition methods, and allows for computed property names in object properties:

function getCar(make, model, value) {
  return {
    // Shorthand for variables
    make,  // Same as make: make
    model, // Same
You can iterate over a Set object using forEach and for...of:

mySet.forEach((item) => { console.log(item); // 1 // 2 // 3 // 'strings' // Object { a: 1, b: 2 } });

for (let value of mySet) { console.log(value); // 1 // 2 // 3 // 'strings' // Object { a: 1, b: 2 } }


Sets also have delete() and clear() methods.

**WeakSet**

Similar to WeakMap, the WeakSet object allows you to hold weak references to objects in a collection, and objects in a WeakSet can only appear once:

var ws = new WeakSet(); var obj = {}; var foo = {};

ws.add(window); ws.add(obj);

ws.has(window); // true ws.has(foo); // false, foo was not successfully added

ws.delete(window); // remove the window object from the collection ws.has(window); // false, the window object has been deleted


### 13. Classes

ES6 includes class syntax. It's important to note that the class here is not a new object inheritance model; it is merely a syntactic sugar representation of the prototype chain.

Use the static keyword within a function to define methods and properties of the constructor:

class Task { constructor() { console.log("task instantiated!"); }

showId() { console.log(23); }

static loadAll() { console.log("Loading all tasks.."); } }

console.log(typeof Task); // function let task = new Task(); // "task instantiated!" task.showId(); // 23 Task.loadAll(); // "Loading all tasks.."


Inheritance and supersets in classes:

class Car { constructor() { console.log("Creating a new car"); } }

class Porsche extends Car { constructor() { super(); console.log("Creating Porsche"); } }

let c = new Porsche(); // Creating a new car // Creating Porsche


extends allows a subclass to inherit from a superclass, and it is important to note that the constructor function of the subclass needs to execute the super() function.

Of course, you can also call the parent class method in the subclass method, such as super.parentMethodName().

Read more about classes here.

There are a few things to note:

- Class declarations are not hoisted, so if you want to use a Class, you must define it before using it, otherwise a ReferenceError error will be thrown.

- You do not need to use the function keyword when defining functions within a class.

### 14. Symbol

Symbol is a new data type, and its values are unique and immutable. The purpose of proposing symbol in ES6 is to generate a unique identifier, but you cannot access this identifier:

var sym = Symbol( "some optional description" ); console.log(typeof sym); // symbol


Note that you cannot use the new operator in front of Symbol.

If it is used as a property of an object, then this property will be non-enumerable:

var o = { val: 10, [ Symbol("random") ]: "I'm a symbol", };

console.log(Object.getOwnPropertyNames(o)); // val


To get the symbol properties of an object, you need to use Object.getOwnPropertySymbols(o).

### 15. Iterators

Iterators allow access to one element of a data collection at a time, and when the pointer points to the last element of the data collection, the iterator will exit. It provides the next() function to traverse a sequence, which returns an object containing the done and value properties.

In ES6, you can set the default iterator for an object by using Symbol.iterator. Whenever an object needs to be traversed, executing its @@iterator method can return an iterator for obtaining values.

Arrays are iterators by default:

var arr = [11,12,13]; var itr = arrSymbol.iterator;

itr.next(); // { value: 11, done: false } itr.next(); // { value: 12, done: false } itr.next(); // { value: 13, done: false }

itr.next(); // { value: undefined, done: true }


You can customize the iterator of an object by [Symbol.iterator]().

### 16. Generators

Generator functions are a new feature in ES6, which allows a function to return an iterable object that generates multiple values.

In use, you will see the * syntax and a new keyword yield:

function *infiniteNumbers() { var n = 1;

❮ Python Docstrings Insertion Sort ❯