Blog

ServiceNow IIFE Scripts

ServiceNow has incorporated IIFE scripts into their latest releases.  What is an IIFE script and what does it mean to you? 

IIFE stands for Immediately-invoked function expression. IIFE is just an anonymous function (no name attached to it) that is wrapped inside of a set of parentheses and called (invoked) immediately.  

From the ServiceNow wiki on this topic:

An immediately invoked function expression is both declared and invoked within the same script field. Whenever you write a script that only needs to run in a single context, such as a transform map script, use this type of function. For functions that must run in multiple contexts, consider reusable functions instead.

What does this mean and how do these scripts help? By enclosing a script in an immediately invoked function expression you can:

  • Ensure 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.

  • liminate having to make separate function calls.

Before IIFE Scripts, we used to add functions ourselves, but now ServiceNow adds the IIFE script automatically to get you started. Along with the new "real-time" syntax checker, scripting is easier than ever!

Examples

IIFE Format

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

IIFE Script with inner functions

(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.

Business Rule

(function executeRule(current, previous /*null when async*/) {

// Add your code here

})(current, previous);

Transform Script

(function runTransformScript(source, map, log, target /*undefined onStart*/ ) {

// Add your code here

})(source, map, log, target);

Basic IIFE

(function() {
// Add your code here
})();