recently used the arrow function in the project frequently, in the process of usingreturn
Keyword usage is more confused. The following methods are recorded:
- If the code block of the arrow function is more than one sentence, you need to use large brackets to include them and use
return
Keyword Return
Example:
const foo = (a, b) => {
a+b;
}
foo(1, 2) // undefined
const foo1 = (a, b) => {
return a+b;
}
foo1(1, 2) // 3
All the parts that are included in brackets If you want to get the return value, you must use itreturn
Keywords return, otherwise returnundefined
。
- If the arrow function only has a line of sentences, it can omit large brackets and omit
return
Keywords.
Example:
const foo = (a, b) => a+b // equivalent to const foo = (a, b) => {return a+b}
foo(1, 2) // 3
Herefoo = (a, b) => a+b
equivalent tofoo = (a, b) => { return a+b }
The above usage can be used to simplify the callback function, see the following example:
// Normal function writing
[1,2,3].map(function (x) {
return x * x;
});
// Arrow function writing
[1,2,3].map(x => x * x);
can be seen, we used the arrow function to omit the function{}
return
Keywords make the function more concise.
Below is my public account QR code picture, welcome to follow.