Function inside a round brackets

Hello, I’m having a trouble figuring out a function inside a round brackets.

Case 1

var testing = (function(){
    // Code here
})(); //<= another round brackets in the last

or Sometimes, it can be like this

Case 2

var testing = (x, y) => ({ //<= round brackets to wrap the curly brackets
    // Code here

Can anyone Explain to me, what does the round brackets mean?

Short answer, “evaluate”:
First one is an IIFE, and is used on FCC for the test code (your code goes inside it). It is just a function that is being executed immediately.

Second one is an arrow function returning an object, and you need to wrap the object in parentheses otherwise JS will get confused.

Long answer for the second one:

Arrow functions allow you to miss off the return keyword when the return value is a single expression:

const add = (a, b) => a + b;

Just returning an object is that. However, curly brackets are also used by JS to denote the body of a function. So this:

const testing = (x, y) => { foo: x, bar: y }

Is not gonna do what you think it’s gonna do (return an object). It will normally throw an error, because it thinks you’re doing:

function testing (a, b) {
  return foo: a, bar: b;

So to fix this, wrap the value you want to return in parentheses, so it evaluates properly as an object:

const testing = (x, y) => ({ foo: x, bar: y })

// Same as
function testing (a, b) {
  return { foo: a, bar: b };

Long answer for first one:

() is how you call a function.

// Define the function
const sayHello = function () {
  return "hi"

// Call the function

You can call the function immediately, where it is defined: this isn’t magic, it’s the same as the above:

const sayHello = (function () {
  return "hi";

The reason for doing this is because of what’s called closure: when a function is stored in memory, both the actual code of the function is stored and the little environment it defines, which includes any variables inside its scope. When you write a function that immediately executes, like the above, everything that lives in that function is kinda isolated from the rest of the program, it won’t leak out. It acts like a module, a container for the code.

For the tests in the ES6 section, it allows the code you write inside it to run in its own scope, that’s why it’s there. Note that the IIFEs are being removed from the FCC challenges, but that change isn’t live yet.


That explanation reaalllly helpful. To be honest, I don’t know what words i must write in google to find solution for this problem, but now everything is clear to me. Thank you for your reply :slight_smile:

1 Like