brain/src/dev/js/es6.md

86 lines
1.2 KiB
Markdown

# Presentation of the main ES6 features
## Spread Operator
It allows an iterable to expand items in it.
```javascript
array = [1, 2];
appended = [3,4];
all = [...aray, ...appended]
console.log(all)
```
This can be usefull in some situations like this one :
```javascript
array = [1, 2, 3, 4];
console.log(Math.min(...array));
```
instead of the old syntax
```javascript
array = [1, 2, 3, 4];
console.log(Math.min.apply(null, array));
```
## Rest Operator
Represent infinite number or args in an array
```javascript
const sum = (...numbers) => {
return numbers.reduce((previous, current) => {
return previous + current;
});
};
```
## Arrow Function
Function can now be written like this
```javascript
const f = (a, b) => a + b;
console.log(f(1,2));
```
instead of
```javascript
function f(a, b) {
return a + b;
}
console.log(f(1,2));
```
## Default parameters
With arrow syntax !
```javascript
const f = (a = 10) => console.log(a);
f();
f(1);
```
## Destructuring (arrays and objects)
With arrays
```javascript
const array = [1, 2];
const [a, b] = array;
console.log(a, b)
```
or objects
```javascript
const person = { name: "Jesus", age: "33" };
const { name, age } = person;
console.log(name, age);
```