fbpx

ES6 IIFEs with fat-arrow functions

ES6 IIFEs with fat-arrow functions

by   Jack Tarantino  |  June 1, 2018  |  0

Writing Immediately Invoked Function Expressions or IIFEs in ES6(Also known as ES2015) just got a lot easier with the introduction of fat arrow functions.

(global => {
  const MY_CONSTANT = 'api key or something'
  let counter = 0
  let some_array = [1,2,34,5,6,7]

  counter = some_array.reduce (total, item) => total + item
})(window)

This is great. Much shorter than the old ES5 way of writing IIFEs. Or if you don’t need to reference the window/global object and you just hate extra characters:

()=> {
  // code goes here...
}()

I would be hesitant to use this second approach in some cases because it’s not immediately clear that the function is going to be invoked immediately. The containing parens(while not super pretty) let you know from line one that this is a function that will be invoked right away. Also be careful using this in fat arrow functions in general. They have a slightly different context than normal functions which can bite you.

As a bit of extra credit there’s an even shorter way to write IIFEs in ES6 which is to use the block context syntax (not super recommended. there’s a reason you probably haven’t ever seen this before) all on its own like so:

// some code...
{
  // whatever happens here is private and invoked immediately
  console.log("I'm executing code immediately!")
}
// more code...

This approach is very fun because it requires the absolute minimum amount of code. It doesn’t allow us to take/pass arguments though so it’s a bit limited in terms of the features we usually use in IIFEs but that shouldn’t stop you if all you want to do is create a new closure to hide private variables from outside code.

This post originally appeared on Jack of Spades. Check out his more recent writing and follow him on twitter!

Sign up for InRhythm updates: IR events, tech news, and more!

Leave a Reply




check out our new interactive scrum framework