ES6+ Cheatsheet

New types

Classes, Inheritance, Setters,Getters

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Rectangle extends Shape {
constructor (id, x, y, w, h) {
super(id, x, y)
this.width = w
this.height = h
}
// Getter and setter
set width (w) { this._width = w }
get width () { return this._width }
}

class Circle extends Shape {
constructor (id, x, y, radius) {
super(id, x, y)
this.radius = radius
}

do_a(x) {
let a = 12;
super.do_a(x + a);
}
static do_b() { ... }
}

Circle.do_b()

Promises

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
new Promise((resolve, reject) => {
request.get(url, (error, response, body) => {
if (body) {
resolve(JSON.parse(body));
} else {
resolve({});
}
});
})
.then(() => {})
.catch((err) => throw err);
// Parallelize tasks
Promise.all([promise1, promise2, promise3]).then(() => {
// all tasks are finished
});

Modules import & export

1
2
3
4
5
6
7
export var num = 50; 
export function getName(fullName) {
//data
};

import {num, getName} from 'module';
console.log(num); // 50

Arrow function

1
2
3
const sum = (a, b) => a + b

console.log(sum(2, 6)) // prints 8

const & let

let

1
2
3
4
5
6
7
8
let a = 3

if (true) {
let a = 5
console.log(a) // prints 5
}

console.log(a) // prints 3

const

1
2
3
4
// can be assigned only once:
const a = 55

a = 44 // throws an error

Default parameters

1
2
3
4
5
6
function print(a = 5) {
console.log(a)
}

print() // prints 5
print(22) // prints 22

String interpolation

1
2
3
4
const name = 'Leon'
const message = `Hello ${name}`

console.log(message) // prints "Hello Leon"

Multiline string

1
2
3
4
console.log(`
This is a
multiline string
`)

string.padStart() & string.padEnd()

1
2
3
4
5
> '1'.padStart(3, 0);
< "001"

> 1.padEnd(7, "X");
< "1XXXXXX"

Spread operator ...

1
2
3
4
5
6
const a = [ 1, 2 ]
const b = [ 3, 4 ]

const c = [ ...a, ...b ]

console.log(c) // [1, 2, 3, 4]

Destructuring

1
2
3
4
5
6
7
8
9
let obj = { 
a: 55,
b: 44
};

let { a, b } = obj;

console.log(a); // 55
console.log(b); // 44

Exponential Operator **

1
2
3
4
5
> 2**2**2
< 16

> 3**3
< 27

for...of

The for..of loop in JavaScript allows you to iterate over iterables (arrays, sets, maps, strings etc).

1
2
3
for (element of iterable) {
// body of for...of
}
  • iterable - an iterable object (array, set, strings, etc).
  • element - items in the iterable

Class properties

1
2
3
4
5
6
7
class Animal {
constructor() {
this.name = "Lion"
}
// directly define class property
age = 0;
}

Generators

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// generator function
function* generatorFunc() {

console.log("1. code before the first yield");
yield 100;

console.log("2. code before the second yield");
yield 200;
}

// returns generator object
const generator = generatorFunc();

console.log(generator.next());

< 1. code before the first yield
< {value: 100, done: false}