Arrow Functions

Arrow functions allow us to write shorter function syntax.

const name = function() 
{
  return "Mary"
}


const name = () => 
{
  return "Mary"
}

 

If the function has only one statement, and the function returns a value, we can remove the curly brackets and the return keyword

const name = () => "Mary"

Note that, if you include curly brackets (ie your function is in a block), then you must include the return keyword

const name = () => {return "Mary"}

 

If a function has only one parameter, we can remove the round brackets

/* With round brackets */
const square = (number) => number * number

/* Without round brackets */
const square = number => number * number

 

An arrow function cannot contain a line break between its parameters and its arrow.

/* Syntax error */
const result = ()
  => 1


/* This is allowed */
const func = () =>
  1
 ;
<div align="center"><a href="file:///C|/Users/Derek/Documents/Notes/versionC/index.html" title="DKIT Lecture notes homepage for Derek O&#39; Reilly, Dundalk Institute of Technology (DKIT), Dundalk, County Louth, Ireland. Copyright Derek O&#39; Reilly, DKIT." target="_parent" style='font-size:0;color:white;background-color:white'>&nbsp;;</a></div>