32

I see a piece of JavaScript code in my Node.js application.

( function() { console.log("gg") } )(this)

I would like to know why use => ( function(){} )(this) this type of structure, and how does this compile.

I am understanding why we have this two brackets ()(), and why this code would work.

1
  • 2
    Ok, the interesting thing is though, why (this) is passed?!? Commented Mar 7, 2014 at 18:35

1 Answer 1

22

This is a self invoking anonymous function. This pattern is useful when you want to hide variables from the global namespace.

(function(){
    var foo = "foo";
})();

console.log(window.foo); // undefined

Also see What do parentheses surrounding a JavaScript object/function/class declaration mean?

What advantages does using (function(window, document, undefined) { … })(window, document) confer?

Sign up to request clarification or add additional context in comments.

3 Comments

How about (function(){})(this); Does "this" invoke this function? How about (function(global, requirejs, require){})(this, requirejs, require) ?
these are just additional parameters which you can pass to the given function I'll fix this in my answer
i think this explains everything you need to know link

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.