/ES5 Version
var getCurrentDate = function (){
return new Date();
}
//ES6 Version
const getCurrentDate = () => new Date();
function(){}
declaration and return keyword needed to make a function and return a value respectively. In the Arrow Function version we only need the ()
parentheses and we don't need a return statement because Arrow Functions have a implicit return
if we have only one expression or value to return.//ES5 Version
function greet(name) {
return 'Hello ' + name + '!';
}
//ES6 Version
const greet = (name) => `Hello ${name}`;
const greet2 = name => `Hello ${name}`;
const getArgs = () => arguments
const getArgs2 = (...rest) => rest​
arguments
object. So calling the first getArgs
func will throw an Error. Instead we can use the rest parameters to get all the arguments passed in an arrow function.const data = {
result: 0,
nums: [1, 2, 3, 4, 5],
computeResult() {
// "this" here refers to the "data" object
const addAll = () => {
// arrow functions "copies" the "this" value of
// the lexical enclosing function
return this.nums.reduce((total, cur) => total + cur, 0)
};
this.result = addAll();
}
};
this
value. It captures or gets the this
value of lexically enclosing function or in this example, the addAll
function copies the this
value of the computeResult
method and if we declare an arrow function in the global scope the value of this
would be the window
object.