IIAF - Immediately Invoked Arrow Function

Datetime:2016-08-22 23:01:28          Topic: ECMAScript           Share

In ES5 we used IIFE’s for block scope and preventing global scope creep, this was quite a common pattern with code in the wild. ES6 has morphed that pattern in conjunction with the arrow function for an even less verbose syntax, the IIAF or Immediately Invoked Arrow Function.

// basic sytnax
(() => {
  console.log('Immediately Invoked Arrow Function', this)
})();
/ => 'Immediately Invoked Arrow Function', window

Do something a little more useful:

(() => {
  'use strict'
  const xhr = new XMLHttpRequest()
  xhr.open('GET', 'http://api.randomuser.me/portraits/')
  xhr.send(null)

  xhr.onreadystatechange = function () {
    if (xhr.readyState !== 4 ) { return }
    if (xhr.status !== 200) { return console.log('Error: ' + xhr.status) }

    console.log(xhr.responseText)
  }
})()

In ES6, tou can easily use a block statement to keep a variable local as well, or better yet a module.

// block
{ 
const foo = 'block scope'
}
console.log(foo)
/ => RefereceError

/* Module */

// lib.js
export default = 3.14
export const obj = { foo: bar };
export function hello() { ... };

// main.js
import * as module from './lib';
console.log(lib.default);
console.log(lib.obj);
console.log(lib.hello);

That said you can still use an IIAF in ES6 to invoke a sequence of statements; beware of loosely binding as not having parens around the arrow function will throw an error.

Just use this sytax:

(() => {})();

It’s worth noting that a paramaterized version will still work:

((x) => {
  console.log('Works fine');
})();




About List