[ES6] ES6 Syntax

ES6 Syntax

let & const

  • let used on variable values
  • const constant values

Arrow Functions

solves issues with this keyword

1
2
3
4
5
const myFunc = () => {

}
// shorter
const multiply number => number * 2;

Exports & Imports

1
2
import * as bundled from './app.js';
import { smith as Smith } from './app.js';

Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Human {
gender = 'male';

printGender = () => {
console.log(this.gender);
}
}
// property
class Person extends Human{
name = 'Max';
gender = 'female';

print = () => {
console.log(this.name);
}
}

// usage
const myPerson = new Person();
myPerson.print();
myPerson.printGender();

Spread & Rest

  • Spread: Used to split up array elements OR object properties
  • Rest: Used to merge a list of function arguments into an array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const numbers = [1, 2, 3]
const newNumbers = [...numbers, 4]

const person = {
name: 'Max',
};

const newPerson = {
...person,
age: 28,
}

// Rest
const filter = (...args) => {
return args.filter(el => el === 1);
}

Destructuring

Easily extract array elements or object properties and store them in variables

1
2
3
const numbers = [1, 2, 3]
[num1, , num3] = numbers;
console.log(num1, num2);

Primitive type & Reference type

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const num = 1;
const num2 = num; // build a real COPY of num

// Reference type: object
const person = {
name: 'Max',
};

const secondPerson = person; // secondPerson is another pointer to the memory

// To create a real copy of object
const secondPerson = {
...person
};

Array Functions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const numbers = [1, 2, 3];

// map
const doubleArray = numbers.map((num) => {
return num * 2;
});

// find
const findNum = numbers.find((num) => {
return num == 2;
});

// filter
const filterNum = numbers.filter((num) => {
return num < 3;
});

// reduce
const reducer = (accumulator, currentValue) => {
return accumulator + currentValue;
}

numbers.reduce(reducer);