Best of Modern JavaScript — Arrow Function Syntax

Image for post
Image for post
Photo by Matt Ridley on Unsplash

Since 2015, JavaScript has improved immensely.

It’s much more pleasant to use it now than ever.

In this article, we’ll look at arrow functions in JavaScript.

Arrow Function Syntax

We can create arrow functions by using the following syntax:

or

or

If we have one parameter, then we don’t need the parentheses.

We can specify the body by writing:

or:

Arrow functions are great for reducing the verbosity of our code.

For example, we can reduce:

to:

Omitting Parentheses Around Single Parameters

We can remove the parentheses if we have a single parameter that doesn’t have a default value.

For instance, we can write:

If we have anything else, we need the parentheses.

We can define default parameters by writing:

Propagating Variable Values

Variable values can be propagated statically or dynamically.

Static propagation is getting variable values from outside the function:

Dynamic propagation is getting variable value from parameters:

Arrow functions don’t bind to their own special values.

These special values include:

  • arguments
  • super
  • this
  • new.target

Arrow Functions Bind Loosely

Arrow functions bind loosely.

If we have:

Then x => (x % 5) === 0 is considered to be part of the function.

To keep the whole expression together as the function, we can wrap them in the parentheses:

We should wrap whatever we want in the function wither parentheses.

No Line Break After Arrow Function Parameters

We can’t add a line break after the arrow function parameters.

For instance, we can’t write:

We’ll get a syntax error if we write that.

Instead, we write:

Then it’ll run.

This way, if our arrow function has only one parameter, we can omit the parentheses and still keep it valid.

No Statements as Expression Bodies

Expressions are code that returns a value.

For instance:

all return something and are expressions.

Statements do things. The following are examples of statements:

Most expressions can be used as statements, just that they don’t do anything.

We can put expressions into arrow functions if it’s one line long and the value will be returned.

For example, we can write:

But we’ve to put statements in braces, so we’ve to write:

Image for post
Image for post
Photo by Nick Fewings on Unsplash

Conclusion

Arrow functions can be defined and used in various ways.

Written by

Web developer. Subscribe to my email list now at http://jauyeung.net/subscribe/. Email me at hohanga@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store