ES6 tips

Learn some awesome tips from the new ES6 standard.

Copy an array

1
2
3
4
const foo     = [4,5,2,7,6];
const fooCopy = [...foo]; // [4,5,2,7,6]

const [first, second] = foo; // 4,5

Template literals

1
2
3
4
const foo = 1;
const bar = 312;

const st = `Foo: ${foo}, Bar: ${bar}`; // Foo: 1, Bar: 312

IIFEs blocks

1
2
3
(function(){
...
})();

It’s now equal to:

1
2
3
{
...
}

Arrow functions

1
2
3
function foo() {
console.log('bar');
};

It’s now equal to:

1
const foo = () => console.log('bar');

And look at this:

1
2
var foo = [1, 2, 3, 4, 5];
var bar = foo.map(function (x) { return x * x });

It’s now equal to:

1
2
const foo = [1, 2, 3, 4, 5];
const bar = foo.map(x => x * x);

String .includes() and .repeat()

1
2
3
4
5
6
const string    = 'fooo';
const substring = 'foo';

console.log(string.includes(substring)); // true

console.log('foo'.repeat(4)); // 'foofoofoofoo'

Default values on parameters

1
2
3
4
5
6
const foo = (...args) => {
for(let arg of args){
console.log(arg);
}
}
foo(3,2,'foo'); // 3, 2, 'foo'

Map

1
2
3
4
const map = new Map();
map.set('foo', 'bar');
map.get('foo'); // 'bar'
map.has('foo'); // true

Also you can iterate over a map:

1
2
3
for (const [key, value] of map.entries()) {
console.log(key, value);
}

For sure, there are more interesting features, but they’ll be shown in further articles… Happy coding!

References