Corkscrew functions

Datetime:2016-08-22 21:37:04          Topic: JavaScript  ECMAScript           Share

Picture a bottle of wine with a corkscrew opener action on it. Like this:

Now picture this:

!+-~(()=>{  })();

Do you get it? Please raise your hands if you do, hi-five!

Yes, it’s JavaScript.

A self-invoking function written in ES6 (ES2015) with some passion for wine and arrow functions. The corkscrew part, i.e. “!+-~” in the front of the parens () is more or less a silent signature and doesn’t by itself influence the execution of the context (code) following it.

Let’s look at the bottle, i.e. enclosure part a bit closely next:

  1. Start with: (function(){  })();      // Anonymous function that’s immediately called.
  2. (() => {  } )();      // Replace the traditional function definition with an arrow function
  3. (() => { /* code wine here */  } )();  // There’s your bottle of wine.

Neat.

Self-invoking functions have been very useful a convention to ship and age beautiful JavaScript plugins. I guess with arrow functions it only gets better, more beautiful.

Here’s an example on using Node’s simple module loading system require within a corkscrew’ed bottle:

<br />!+-~((r)=>{

const circle = r('./circle.js');

console.log( `The area of a circle of radius 4 is ${circle.area(4)}`);

})(require);

Done.





About List