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
  • 5,903
  • 4
  • 39
  • 70
Robert Rocha
  • 9,510
  • 18
  • 69
  • 121

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
  • 4,856
  • 4
  • 30
  • 60