function definition
let timesTwo = params => params * 2
// or
let timesTwo = params => {
return params * 2;
}
console.log(timesTwo(4));
=> 8
no binding of this needed, automatically uses this of where the function is defined
let obj = {
id: 42,
counter: function counter() {
setTimeout(() => {
console.log(this.id);
}, 1000);
}
};
spread operator for args
var arr = [2, 4, 8, 6, 0];
var max = Math.max(...arr);
console.log(max);
=> 8
copy array without mutating the original array
var arr = ['a', 'b', 'c'];
var arr2 = [...arr];
arr2.push('d');
console.log(arr);
=> ['a', 'b', 'c']
console.log(arr2);
=> ['a', 'b', 'c', 'd']
Combine two arrays
var mid = [3, 4];
var arr = [1, 2, ...mid, 5, 6];
console.log(arr);
=> [1, 2, 3, 4, 5, 6]
Remove attr from object
let song = { artist: 'Coolio', length: 210, title: 'gangsta\'s paradise' }
const { artist, ...rest } = song;
console.log(artist);
=> 'Coolio'
console.log(rest);
=> { length: 210, title: 'gangsta\'s paradise' }
const songPlays = { ...rest, playCount: 0 };
console.log(songPlays);
=> { length: 210, title: 'gangsta\'s paradise', playCount: 0 }
const obj = { first: 'Jane', last: 'Doe' };
const { first, last } = obj;
console.log(first);
=> 'Jane'
console.log(last);
=> 'Doe'
class Foo {
constructor(x) {
this.x = x;
this.y = 432;
}
point() {
return 'Foo(' + this.x + ', ' + this.y + ')';
}
}
let myfoo = new Foo(99);
console.log(myfoo.point()); // prints "Foo(99, 432)"