JavaScript: The React Parts

Arrow Function

The next syntax we will talk about is arrow function.

The traditional way of declaring a function are:

js

With arrow function:

js

Compact syntax

Other than the fact that => is shorter than writing the whole function keyword, there are a few usages of arrow function that make your code more compact.

  1. No parentheses required for single parameter

    js
  2. Implicit return for single expression

    js

    There is one pitfall for this second behavior: if you return an object, you need to wrap it with parentheses because JavaScript engine couldn't tell if the curly brace is the beginning of a function or the beginning of an object.

    js

Those compact syntaxes would make your code much more shorter, especially in two common JavaScript use cases:

  1. Currying (no worries if you not sure what is currying, we will discuss it in more details later)

    js
  2. Inline function

    js

Exercise

Rewrite the following functions with arrow function to make them more compact

js
Comments
Reply
Malcolm Kee on June 25, 2019, 6:04 AM

Answers for the exercise are available here.

Issue on this page? Report here