Home>Article>Web Front-end> A summary of JavaScript arrow function syntax
JavaScript arrow function syntax summary
1. When there are no parameters
var demo = function(){ }
Equivalent to:
var demo = () => { }
2. When there is only one parameter
var demo = function(a){ return a; }
Equivalent to:
var demo = a => a
3. Multiple parameters Parentheses need to be used, and the comma separation between parameters
var demo = function(a,b){ return a+b; }
is equivalent to:
var demo = (a,b) => a+b
4. Multiple statements in the function body need to use curly braces
var demo = function(a,b){if(a>b){ return a-b;} else{ return b-a; }}
Equivalent to:
var demo = (a,b) =>{if(a>b){ return a-b;} else{ return b-a; }}
5. When returning an object, you need to wrap it in parentheses, because the curly braces are occupied and interpreted as a code block
var demo = (name,age) =>{return ({ name: name, age: age })}
6. As an array sorting callback
var arr = [1, 9 , 2, 4, 3, 8].sort((a, b) => { if (a - b > 0 ) { return 1 } else { return -1 }})
Note:
Arrow functions are indeed different from traditional functions, but they still have common characteristics.
For example:
1. Typeof operation on arrow function will return "function".
2. The arrow function is still an instance of Function, so the execution method of instanceof is consistent with the traditional function.
3. The call/apply/bind method still applies to arrow functions, but even if these methods are called to expand the current scope, this will still not change.
4. The biggest difference between arrow functions and traditional functions is that the new operation is disabled
Recommended tutorial: "js basic tutorial"
The above is the detailed content of A summary of JavaScript arrow function syntax. For more information, please follow other related articles on the PHP Chinese website!