ES6 IIFE with fat arrow functions

Writing Immediately Invoked Function Expressions or IIFEs in ES6(Also known as ES2015 now) 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

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 new function context syntax all on its own like so:

  console.log("I'm executing code immediately!")

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.