2
(()=>{
console.log("Hello, world");
})();

How does this function work? It seems very obfuscated and I'd like a walkthrough of what's really happening.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
kotAPI
  • 1,073
  • 2
  • 13
  • 37

3 Answers3

3

The expression,

() => {
console.log("Hello, world");
}

creates an Arrow function, introduced in the ECMAScript 2015 standard, and that is immediately executed with the function call expression () at the end.


Moreover, Arrow function definitions are actually function expressions only. So, you can omit the surrounding parens and write it as

() => {
  console.log("Hello, world");
}();

Apart from that, you have only one expression inside the arrow function. So, you don't need to create a block and write the same as

(() => console.log("Hello, world"))();
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
3

This is ECMAScript 6. It creates an anonymous function, using the => (called the "arrow" or "fat arrow") operator. The function does console.log("Hello, world"); when executed. The code you posted then executes that function (the trailing ();).

It breaks down like this:

( // wrapper for the function definition
    ()=>{ // use => to create an anonymous function
        console.log("Hello, world"); // body of the function
    } // end of the function definition
) // end of the wrapper for the function definition
(); // executes the function.

You can read more about arrow functions in this prior answer that I posted or in the Mozilla documentation.

Community
  • 1
  • 1
elixenide
  • 44,308
  • 16
  • 74
  • 100
2

it outputs a message to the web console. Here is a link to a page with the full API.

Rick Runowski
  • 346
  • 3
  • 9
  • Welcome Rick. While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – StuperUser Nov 10 '15 at 17:15