Arrow Functions are one of the most impactful changes in ES6/ES2015, and they are widely used nowadays. They slightly differ from regular functions. Find out how
Arrow函数是ES6/ES 2015中最具影响力的变化之一,目前已被广泛使用。它们与常规函数略有不同。了解如何
Arrow functions were introduced in ES6 / ECMAScript 2015, and since their introduction they changed forever how JavaScript code looks (and works).
箭头函数是在ES6 / ECMAScript 2015中引入的,自从引入以来,它们永远改变了JavaScript代码的外观(和工作方式)。
In my opinion this change was so welcoming that you now rarely see the usage of the function keyword in modern codebases. Although that has still its usage.
在我看来,这个变化是如此的受欢迎,以至于你现在很少看到在现代代码库中使用function关键字。尽管它仍然有它的用途。
Visually, it’s a simple and welcome change, which allows you to write functions with a shorter syntax, from:
从视觉上看,这是一个简单而受欢迎的变化,它允许你用更短的语法编写函数,从:
const myFunction = function() {
//...
}
to到
const myFunction = () => {
//...
}
If the function body contains just a single statement, you can omit the brackets and write all on a single line:
如果函数体只包含一条语句,你可以省略括号,将所有语句写在一行中:
const myFunction = () => doSomething()
Parameters are passed in the parentheses:
参数在括号中传递:
const myFunction = (param1, param2) => doSomething(param1, param2)
If you have one (and just one) parameter, you could omit the parentheses completely:
如果你有一个(而且只有一个)参数,你可以完全省略括号:
const myFunction = param => doSomething(param)