ES6 Arrow Functions

In ES6, a new form of arrow function was added, which is actually a function;


Here's a brief look at :

< script >
let func = canshu => canshu;
console . log ( func ( 3 ));
</ script >


Above we defined a function in the form of an es6 arrow function;

let is equivalent to the previous var, used to define variables, but let has the nature of block-level scope;

func represents the function name;

The equal sign = is followed by our parameters;

After the arrow is our return value;


Compare and see :

< script >
//es6 way
let func = canshu => canshu;
console . log ( func ( 3 ));
// before our way
function func ( canshu ){
return (canshu);
}

//or write like this
var func = function ( canshu ){
return (canshu);
}
</ script >


The arrow function above defaults to one parameter. What if we have multiple parameters?

It's as simple as enclosing the parameters in parentheses:

< script >
//es6 way
let func = ( canshu1 , canshu2 ) => canshu1 + canshu2;
console . log ( func ( 3 , 2 ));
</ script >



The return of the above function is the case when there is only one statement. According to the above writing method, it will return by default, but there is rarely only one statement in the function.

Let's see how to write it in the case of multiple statements?

< script >
//es6 way
let func = ( canshu1 , canshu2 ) => {
if (canshu1 > canshu2){
return canshu1;
} else {
return canshu2;
}
};
console . log ( func ( 3 , 8 ));
</ script >


First of all, multiple statements need to be added after the arrow function { Statements are written in it }

Second, the return value needs to be written explicitly, that is, return + result;


After understanding the above parts, you can basically use arrow functions. For more details, please refer to the documentation;      

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324613489&siteId=291194637