Arrow Function Expressions

Relatively new addition to the language, they provide a more compact form for anonymous functions:

const mean = (x, y) => {
  return (x + y) / 2;
};

Notes on the syntax:

  • Function parameters are provided in parentheses proceeding the fat arrow (=>)
    • Parentheses are optional for a single parameter.
    • Use empty parentheses if no parameters.
  • Function body is contained within curly brackets following the fat arrow (=>)
    • Curly brackets are optional when the function body is made up of a single statement.
    • If that single statement is a return statement, you can also eliminate the return keyword.
    • If the single return statement involves returning an object, to avoid confusion between curly brackets for object literal with curly brackets for the function body, surround the object literal in parentheses.
      const user = username => ({ username });
      
      is the same as
      const user = (username) => {
        return { username };
      };
      

Arrow functions are commonly used for declaring functions as arguments to other functions:

const numbers = [1, 2, 3, 4, 5, 6, 7];

const evens = numbers.filter(x =>  x % 2 === 0);

console.log(evens);

Arrow functions do not exhibit all behaviors of normal (named or anonymous) JavaScript functions. We will explore some of their limitations in later sections.