I'm writing a JavaScript style-guide for my team, so that we can organise and contribute our documents easier. But I've hit a small bump which is where my question applies…
What am I supposed to call an anonymous JavaScript function that's called immediately. I know I could quite simply call it an "anonymous function", but I'd like to stress the fact that it's being called immediately.
Here is an example:
var MyVariable = (function(data){
return "another value"
})("some value");
console.log(MyVariable);
// "another value"
Best Answer
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:
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:
When they are used
IIFEs are used for code that only needs to run once within a task, rather than being repeatedly called.