Variations and Gotchas of the Arrow Function Syntax in JavaScript

ES6 introduced into JavaScript the extremely useful syntax for defining functions known as arrow functions. This refers to the notation:

argument => result

 

Arrow function notation can be used for both named and unnamed (anonymous) functions. Arrow functions allow for very compact definitions.

Example: define the successor function:

const f = ( x => x + 1 )

The parentheses around the function can be dropped:

const f = x => x + 1

It is slightly unclear when seen for the first time but soon becomes very natural.

Note that the above does not require a return; the expression on the right hand side of the arrow is the returned value.

If more than one statement is needed to define the function, braces must be introduced. The above example can also be written as:

const f = x => {
  const result = x + 1
  return result
}

Note that the following is problematic:

const f = x => { x + 1 } // does not return

This is very important: if braces are used, a return statement is necessary.

In short, if braces are present, a return statement is needed; if more than one statement is used in the function, braces must be used.

Another valid form:

const f = x => { 
  return x + 1
}

The argument list can be made explicit with parentheses:

const f = (x) => {
  return x + 1
}

This is required for functions of  multiple arguments, as in the following example:

const sum = (x, y) => x + y

The parentheses around the argument list cannot be dropped in this case.

A function with zero arguments also requires the parentheses around the (empty) argument list as follows:

const f = () => value

 

Leave a Reply

Your email address will not be published. Required fields are marked *