简体   繁体   中英

What happens behind the scenes with this Javascript code?

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

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

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"))();

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM