React ES6 Arrow Functions

Introduction to Arrow Functions in React

ES6 introduced a concise way to write functions in JavaScript known as arrow functions. These functions allow for shorter syntax and an easier way to handle scoping of the this keyword.

Tutorials dojo strip




What are Arrow Functions?

Arrow functions provide a more succinct syntax for writing functions:

JS

With arrow functions, we can rewrite the same function in a more concise form:

JS




Simplifying Further

If the function contains only a single statement that returns a value, we can omit the curly braces and the return keyword, This simplification works as long as there’s just one statement in the function.:

JS




Handling Parameters

Arrow functions can also accept parameters. Here’s how to write an arrow function with parameters:

JS

If there’s only one parameter, the parentheses can be omitted:

JS




How Does this Work?

One of the key differences between arrow functions and regular functions is how they handle the this keyword. Arrow functions do not have their own this context; instead, this refers to the context in which the arrow function is defined.

In contrast, regular functions bind the this keyword to the object that calls the function, which can sometimes lead to unexpected behavior.




Regular Function vs Arrow Function Example

Let’s compare how this is handled in a regular function and an arrow function:

JS


In contrast, here’s how it works with an arrow function:

In these examples, the regular function returns different objects (window and button), while the arrow function consistently returns the Widget object.

JS

Tutorials dojo strip