Arrow functions were introduced in ES6. They allow us to write shorter function syntax and
solve one of the most frustrating problems in JavaScript: the behavior of the
this keyword.
An arrow function uses the => (fat arrow) operator.
// Traditional
const x = function(x, y) {
return x * y;
}
// Arrow
const y = (x, y) => x * y;
If the function has only one statement, and that statement returns a value, you can remove
the brackets {} and the return keyword.
// Shortest version
const hello = () => "Hello World!";
If there is only one parameter, you can omit the parentheses as well.
// One parameter
const greet = name => "Hello " + name;
In regular functions, the this keyword represented the object that called the
function, which could change depending on the context. In arrow functions,
there is no binding of this.
Instead, this inside an arrow function refers to the
parent scope (lexical scoping) at the time it was defined. This makes
arrow functions perfect for things like setTimeout or event listeners where
this usually gets lost.
const person = {
name: "Mim",
// BAD: sayHi will point to the Window object, not person
sayHi: () => {
console.log("Hi " + this.name);
}
}
=> is used to define arrow functionsthis from their surrounding
context (lexical this)new
with an arrow function)