ES6 allows functions to be defined using arrows (=>). If you know Lambda expressions in Java, it makes sense to step back and understand the arrow functions in ES6.

Let’s take a look at the content of ES6.

Start with transformation

First, let’s start with an example of how we typically write in ES5.


var sum1 = function(num1, num2) {
    return num1 + num2;
};
Copy the code

So, what does it look like if I transform it into an arrow function?

var sum2 = (num1, num2) => { return num1 + num2; };Copy the code

The argument list in curly braces is separated from the code in curly braces by =>. This is the beauty of the arrow function, which simplifies our code by making it much more concise.

This can be further simplified if the block of code for an expression is simply an expression followed by a return.


var sum3 = (num1, num2) => num1 + num2;
Copy the code

If a method has only one argument.

Console. info("=> ES5 "); var curf1 = function(v) { return v; };Copy the code

We can even omit the parentheses.

Console. info("=> ES6 "); var curf2 = v => v;Copy the code

If a method has no parameters.

Console. info("=> ES5 "); Var f1 = function() {return ""; };Copy the code

We can still provide a pair of empty parentheses, as if the method had no arguments.

Console. info("=> ES6 "); Var f2 = () => ";Copy the code

As an exception, if the arrow function returns an object directly, parentheses must be placed around the object.

Console. info("=> ES5 "); Var f3 = function() {return {real_name: "LiangGzone"}}; console.log(f3()); Console. info("=> ES6 "); Var f4 = () = > ({real_name: "Liang Guizhao", nick_name: "LiangGzone}"); console.log(f4());Copy the code

About the deconstruction

We can also use the ES6 destruct assignment feature. ES5, that’s what I wrote before.


var f5 = function(person) {
    return person.first + ' ' + person.last;
}
Copy the code

This becomes easier to understand when using the ES6 destruct assignment feature.


const f6 = ({ first, last }) => first + ' ' + last;
Copy the code

Tell me something about the case

Give two examples from Ruan Yifeng’s Introduction to ECMAScript 6.

The callback function

We often use callback functions, the usual way before.

Console. info("=> ES5 "); Var x1 = [1,2,3]. Map (function (x) {return x * x; }); console.info(x1);Copy the code

So, now we can retrofit.

Console. info("=> ES6 "); Var x2 = [1,2,3]. Map (x => x * x); console.info(x2);Copy the code

Rest parameter combination

Instead of using the arrow function, before, our code might look like this.

Console. info("=> ES5 "); var x3 = function(... nums){ return nums; } console.info(x3(512, 1024));Copy the code

So, now we can retrofit.

Console. info("=> ES6 "); var x4 = (... nums) => nums; console.info(x4(512, 1024));Copy the code