JavaScript Introducing ES2015 ES2015 Basics Let and Const

Catalin Radu
Catalin Radu
6,037 Points

Why is the code wrapped in round brackets?

It's first time when I see this and I don't understand what is doing.

(function () {
  // some code here
})();

1 Answer

Jacob Mishkin
Jacob Mishkin
23,080 Points

It's a Immediately Invoked Function Expression, which is a is a design pattern that invokes a self executing anonymous function. There are two parts to this design pattern. First is the JavaScript (function () { Here what is happening is the creating an anonymous function that is scoped to just that function. the second part is the () at the end of the function block. This creates an immediately executing function expression, and the JavaScript interpreter will directly invoke the function. Here is an example:

(function () { 
    var aName = "Barry";
})();
// Variable name is not accessible from the outside scope
aName // throws "Uncaught ReferenceError: aName is not defined"
Catalin Radu
Catalin Radu
6,037 Points

Thank you very much! Now it's more clear for me.

Jacob Mishkin
Jacob Mishkin
23,080 Points

Right on! Glad I could help.