Showcaselfloyd
Showcaselfloyd

Reputation: 838

What do parenthesis around function in JavaScript mean?

I'm working on a app that's build on Java and JavaScript and I found some code today I couldn't make sense of.

 var myVariable = (function(configObj){
    var width = configObj.width;
    var height = configObj.height;
 })

 gadgetFuncArray.push(myVariable);

Which I think makes an array of functions? But I'm not sure why you would want to push a bunch of config options as an array of functions.

Thoughts

Upvotes: 0

Views: 168

Answers (2)

broguinn
broguinn

Reputation: 591

In your example, the parentheses are functionally useless, and could easily be removed. People sometimes (though less commonly since ES6) use these parentheses to create an IIFE. From the Wikipedia page:

Immediately-invoked function expressions can be used to avoid variable hoisting from within blocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined within the function.

Which would look something like: (function () {})()

I would recommend reviewing Kyle Simpson's detailed ebook You Don't Know JS, particularly the sections on scope and closures.

Upvotes: 1

Rob M.
Rob M.

Reputation: 36511

Wrapping a function in parenthesis does nothing special, that is typically used for IIFE's when you want to immediately call the function after declaring it:

var module = (function foo(config) {
   return {
      getConfig: function() {
         return config.my;
      }
   }
}({ my: 'config' }));

But that doesn't seem to be happening in the code you posted. There are reasons that one would want an array of functions, though it is not overly apparent in the posted code.

Upvotes: 1

Related Questions