Javascript Upgrade: Arrow functions

J

This is part of my series about upgrading my Javascript skills.

  1. Previous:
  2. Javascript, I hardly knew ya
  3. Javascript Upgrade: Day 1
  4. Javascript Upgrade: let/const

Next on my list of topics to learn are arrow functions.  I’ll fully admit to being completely confused by these when I started to get into React stuff.  I’d see them and try to use them but I never took the time to understand them.  Today that has changed.

Arrow functions are a more concise where to create functions in Javascript.  They have minimal syntax and allow for implicit returns(meaning you don’t have to explicitly say return x).  I’ve included a few examples below but the rules are pretty simple.

Their most basic form is (params) => { body }

Some changes though.

  • If you have a single param you can leave off the first set of brackets.
  • If you want an implicit return leave off the second set and make sure your body fits on a single line.
  • If you want to return an object literal you need to wrap the body in ().
const data = [1, 2, 3, 4, 5, 6];
//with multiple params
(x, y) => { x + y }

//with param and brackets
const even = data.filter((i) => { i % 2 == 0 })

//return object literal
var name = () => ({name: "Shawn"})

//with single param you can leave off the first set of brackets
const even2 = data.filter(i => { i % 2 == 0})

//with an implicit return you can leave off the second set as well
const even3 = data.filter(i => i % 2 == 0)

//they are anonymous but can be assigned to variables
const isEven = (num) => num % 2 == 0

isEven(2) //true
isEven(3) //false

Other things to be aware of this is not rebound inside an arrow function.  I know in React not using arrow function I had to bind(this) everywhere and from what I can see with arrow functions going forward I can avoid that.

I feel like arrow functions will be really useful to me and I’ve already seen them in use a lot but it’ll still take me time to recognize them at first glance.  Even more so given the variety allowed in brackets or not.  The stuff about this will require more practical usage to really become apparent.

About the author

Add comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

By shawn

Other Things