The evolution of an arrow function

Summary

As a reminder to me, and I hope, a help to others here are the various ways in which JavaScript arrow functions can be used to reduce the amount of code you write.

Less is more ?

Here I start with an old fashioned JavaScript function being used as an argument to the map function and then step by step reduce the amount of the code to take full advantage of the possibilities of JavaScript arrow functions. Not all of these steps would be possible in all circumstances.

//Test data is an array of integers
const nums = [1,2,3,4,5,6,7,8,9,10]

//We start by using a 'traditional' 
//function definition as our argument 
//to 'map'
const first_approach = nums.map(
  function(n){
    return num * 2
  }
)

//Convert the 'traditional' function 
//definition to an arrow function
const second_approach = nums.map((n) => {
    return n * 2
})

//When there's only one argument to the 
//function we can remove the brackets 
//around the argument, so 'n' is no 
//longer bracketed
const third_approach = nums.map(n => {
    return n * 2
})

//Because only one thing is being 
//returned the processing can all be 
//placed on one line ...
const fourth_approach = nums.map(n => { return n * 2 })

//Take advantage of the implicit return 
//within an arrow function so we no longer 
//need to use 'return' and, in the process, 
//do away with the curly brackets.
const fifth_approach = nums.map(n => n * 2 )


Summary

So just to summarise, in the right circumstances it’s possible to go from this …

//Longest version
const first_approach = nums.map(
  function(n){
    return num * 2
  }
)

… to this .

//Shortest version
const fifth_approach = nums.map(n => n * 2 )

Full Details

Fuller details about when all of these optimisations are possible are available on the excellent MDN Arrow Function page.

Leave a Reply

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