Functions - SelfishHellfish/JS_Ref GitHub Wiki

Closures

are functions within functions that are aware of their environment, which consists of the parent function's scope as well as the global one. are often used in callbacks, as they allow for the local environment of their parent function to be stored e.g. given function parent(input) {var tobestored = "storedvalue"; return function() {return tobestored*2}}, parent(somevalue) can be assigned to a variable and executed later with thatvariable(); ie tobestored was stored in the closure/inner function for later execution.

Immediately invoked function executions (IIFEs)

are functions that are automatically executed when a script is run, without being specifically called. IIFEs can be used to prevent global scope pollution which may be useful when working on large projects or with third party packages/libraries. e.g. (function test() {testvar='nonPollutingVar'; console.log('testvar'})()

Useful methods and properties

the arguments variable exists in every function and is an object containing all of the arguments passed to the function
functionName.name returns the name of the function. useful when functions are dynamically defined i.e. when a function is assigned to a variable
functionName.length returns the number of arguments that the function expects
functions cheat sheet