Meaning of "naked" round brackets without a name

Hi!

I understand arrow functions and such but i got presented with a pair of “naked” round brackets like this:

(() => {
  "use strict";
  // code
})();

What is the meaning of this? Is it just to be able to run an anonymous arrow function without assigning the return value to a variable?

It’s how you execute functions. If

function doSomething() {
  // do something
}

Is a function, then

doSomething()

Executes it, that’s what the () is for. And in theory you could have executed it as soon as it was defined if you wanted to, like

function doSomething() {
  // Do something
}()

But you can’t really do that because of the keyword at the start, you need to trick the parser slightly, so maybe you do this instead

(function doSomething() {
  // Do something
})()

Etc. It’s creating a scope inside the function.

empty arrow function that actually does nothing

https://gist.github.com/wklug/5b0a614835a7fb302cd4e2561b2d4246

Thanks for the great answer! I understand now, and it seems to me that it’s quite unnecessary to do like this in this case because you could do it without the arrow function in the normal code flow.

It is for the strict mode, it needs to be done that way - or it needed, now strict mode shouldn’t need to be invoked and can work without the function

You mean that strict mode is default nowadays?

I don’t know the details, but the challenges are being updated to not invoke it anymore but behave the same so I imagine it is like that

1 Like