What's the point of a "()" at the end of a function definition in JavaScript?

Question:

I was looking at some code to avoid using global variables and functions:

myNameSpace = function() {
	var current = null;
	function init() {
		…
	}
	function change() {
		…
	}
	function verify() {
		…
	}
	return{
		init:init,
		set:change
	}
}();

Calling myNameSpace.set() now invoke the change() method.

I have many doubts about the purpose of the last pair of parentheses, what are they used for?

Answer:

What the two parentheses at the end do is execute the function that precedes it. That is, imagine the following:

myFunc = function(){ /* codigo */ }

what it does is assign a function (the implementation) to a function, so if we do

myFunc();

the function will be executed as it is being invoked (or in a very informal way, the parentheses have been added to execute it).

If we now return to the code of your question, we have:

myNamespace = function(){ /* codigo */ }();

what happens is that the function is being defined and immediately it is being executed. This concept is known as self-executing functions (IIFE, " Immediately-invoked function expressions "), since as the name suggests, they are executed immediately after being defined.

Another very common way of seeing them is in the form:

(function() {})() ó (function() {}())

But they both do the same thing, run the function.

Knowing that, if you go back to the original code, what those parentheses will do is immediately execute the function and assign the object returned by the return to myNamespace .

Scroll to Top