They already have a term for that in the Javascript world. They are called Immediately Invoked Function Expressions (IIFE).
What it is
IIFE functions are not given a name. Instead, they are executed once as the interpreter comes across them:
var area = function() {
var width = 3;
var height = 2;
return width * height;
}();
The final parentheses after the closing curly brace of the code block tell the interpreter to call the function expression immediately.
If you write a function declaration you must add grouping operators, or parentheses surrounding the function, to tell the interpreter to treat the function as an expression that can be immediately invoked:
var area;
(function() {
var width = 3;
var height = 2;
area = width * height;
}());
When they are used
IIFEs are used for code that only needs to run once within a task, rather than being repeatedly called.
- As an argument when a function is called (to calculate values, etc.)
- To assign the value of a property to an object.
- In event handlers and listeners.
- To prevent conflicts between two scripts that might use the same variable names. They can be used as wrappers to drop code in another script where you're not sure if variable names may be the same.