1

I am learning about JavaScript functions on MDN

I came across an example that looks similar to this:

var saySomething = ( function(){console.log("hello")} )();

I have also seen this in the jQuery source.

I have not found any explanation of this style of function calling/definition on the MDN function reference.

I know from running the code that it calls itself immediately upon interpretation by the JavaScript engine.

Is this the Grouping Operator in action? Where it says:

  1. First evaluate the body of this function and return it
  2. Since the parentheses () immediately follow it it gets called ?
Andrew Hendrie
  • 6,205
  • 4
  • 40
  • 71
Robert
  • 10,126
  • 19
  • 78
  • 130

1 Answers1

2

Google "Immediately Invoked Function Expression" or "IIFE".

The general syntax looks like this:

(function(){
// do something here
})():

Sometimes you'll see arguments passed in as well. It's basically used to wrap your code so none of your variables leak out into the global namespace.

shmuli
  • 5,086
  • 4
  • 32
  • 64