Immediate functions are used to create a scope for initialization code or for one execution of some functionality. In these situations, creating a named function is a waste of memory and therefore an immediate function is a good solution. Immediate functions can get parameters and can return values. Here is an example that include the use of parameters and return value:
In the example, the message parameter is set to the hello value and is returned by the immediate function. After executing the code a ‘hello’ will be written to the console.
Writing the Library’s Immediate Function
The code is an immediate function that declares a scoped variable (ns) that is going to be used inside the library as its namespace. In the execution of the immediate function, the this keyword is used to create the namespace object in the global scope and then to pass it as a variable to be used inside the library.