Review: Anonymous Functions

Anonymous refers to not having a name or any means of identification. When using an anonymous function in JavaScript, your function will not be named. For example, let x = function() { console.log("I am anonymous"); }; In this case, "x" is the variable assigned to the anonymous function and NOT its actual name.

Self-Executing Anonymous Functions

A common pattern in JavaScript is the self-executing anonymous function. This pattern creates a function expression and then immediately executes the function. This pattern is extremely useful for cases where you want to avoid polluting the global namespace with your code - no variables declared inside of the function are visible outside of it.

Example: A self-executing anonymous function

(function(){
var foo = 'Hello world';
})();
console.log(foo);   // undefined!


Source: Rebecca Murphey, https://autotelicum.github.io/Smooth-CoffeeScript/literate/js-intro.html#self-executing-anonymous-functions
Creative Commons License This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License.

Last modified: Monday, September 11, 2023, 9:59 AM