Home > Web Front-end > JS Tutorial > A summary of JavaScript arrow function syntax

A summary of JavaScript arrow function syntax

coldplay.xixi
Release: 2020-06-15 16:02:22
forward
2345 people have browsed it

A summary of JavaScript arrow function syntax

JavaScript arrow function syntax summary

1. When there are no parameters

var demo = function(){
}
Copy after login

Equivalent to:

var demo = () => {
}
Copy after login

2. When there is only one parameter

var demo = function(a){
return a;
}
Copy after login

Equivalent to:

var demo = a => a
Copy after login

3. Multiple parameters Parentheses need to be used, and the comma separation between parameters

var demo = function(a,b){
return a+b;
}
Copy after login

is equivalent to:

var demo = (a,b) => a+b
Copy after login

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;
  }}
Copy after login

Equivalent to:

var demo = (a,b) =>{if(a>b){
    return a-b;} else{
    return b-a;
  }}
Copy after login

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   })}
Copy after login

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 }})
Copy after login

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!

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template