Immediately invoked function expressions

An immediately invoked function expression (IIFE) is both declared and invoked within the same script field.

The system uses immediately invoked function expressions when a script runs in a single context, such as in a transform map script. Functions that run from multiple contexts use Script includes instead.

By enclosing a script in an immediately invoked function expression, you can:
  • Ensure that the script does not impact other areas of the product, such as by overwriting global variables.
  • Pass useful variables or objects as parameters.
  • Identify function names in stack traces.
  • Eliminate having to make separate function calls.

An immediately invoked function expression follows this format:

(function functionName(parameter){
 
  //The script you want to run
 
})('value');//Note the parenthesis indicating this function should run.

You can declare functions within the immediately invoked function expression. These inner functions are accessible only from within the immediately invoked function expression.

(function functionName(parameter){
 
  function helperFunction(parameter){//return some value}
 
  var value = helperFunction(parameter);//Valid function call.
 
  //perform any other script actions
 
})('value');
 
var value2 = helperFunction(parameter);//Invalid. This function is not accessible from outside the self-executing function.