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,455
  • 3
  • 37
  • 64
Robert Rocha
  • 8,656
  • 15
  • 59
  • 110

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,576
  • 3
  • 28
  • 58