Original article could be read here.
Help to write functions very quickly. This feature is known as lambdas in other language.
ES5:
"use strict";
var salary = [10000, 20000, 30000];
var with1000Increment = salary.map(function (x) {
return x + 1000;
});
ES2015:
var salary = [10000, 20000, 30000];
var with1000Increment = salary.map(x => x + 1000);
For more than one argument,
ES5:
"use strict";
var marks = [89, 10, 70];
marks.sort(function (a, b) {
return b - a;
});
ES2015:
var marks = [89, 10, 70];
marks.sort((a, b) => b-a);
If you are writing JavaScript, I hope you know what "self" is and how ugly it is. We can easily avoid it with arrow functions.
ES5:
'use strict';
$('meta').each(function () {
var _this = this;
setTimeout(function () {
console.log(_this.name);
}, 100);
});
ES2015:
$('meta').each(function() {
setTimeout(() => {
console.log(this.name);
}, 100);
});
Even though arrow functions are handy, don't use arrow functions everywhere. If you use an arrow function for "each" callback in the below code block,
ES2015:
$('meta').each(() => {
setTimeout(() => {
console.log(this.name);
}, 100);
});
You won't get the this
context assigned by jQuery. So, use them with care.
ES5:
'use strict';
$('meta').each(function () {
setTimeout(function () {
console.log(undefined.name);
}, 100);
});
ES5:
"use strict";
var name = "Arunoda";
var user = {
name: name,
getAddress: function getAddress() {
return "Colombo. Sri Lanka";
}
};
ES2015:
var name = "Arunoda";
var user = {
name,
getAddress() {
return "Colombo. Sri Lanka";
}
};
Here's how we can concatenate a string without using the "+" operator.
ES5:
"use strict";
var name = "Arunoda";
var address = "Colombo, Sri Lanka";
var greeting = "My Name is " + name + " and I live in " + address;
ES2015:
var name = "Arunoda";
var address = "Colombo, Sri Lanka";
var greeting = `My Name is ${name} and I live in ${address}`;
You can reduce the amount of code and self-document it. Let's say we have a user object and we are only interested in the name
field.
ES5:
"use strict";
var user = { name: "arunoda", address: "Colombo. Sri Lanka" };
var name = user.name;
ES2015:
var user = {name: "arunoda", address: "Colombo. Sri Lanka"};
var {name} = user;