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.

6
  • 3
    Search for "ES6". () => is (almost) the same as function (), so this is a anonymous function that's immediately invoked. See also this result via babel. Commented Nov 10, 2015 at 16:53
  • First of all this is ES6 code, so not implemented everywhere for the moment Commented Nov 10, 2015 at 16:54
  • 2
    See also the IIFE pattern Commented Nov 10, 2015 at 16:56
  • @StrandedKid: Works in Chrome for me. Commented Nov 10, 2015 at 17:36
  • @FelixKling Yep but still it doesn't work everywhere :) Commented Nov 10, 2015 at 20:05

3 Answers 3

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"))();
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

2

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.