Javascript Function Usage Patterns

In programming, patterns mostly apply to code design. However, patterns may also apply to usage of language specific functionality, either to ensure best practices or to avoid common issues. Patterns below focus on function usage patterns.

Functions in JavaScript are of two types:

  • Named functions: functions having a given name (e.g.: function functionName() {} )
  • Anonymous functions: function without a given name, also known as function expressions (e.g.: var functionName = function() {} or call( function() {} ) )

A note worth considering, before diving into function patterns, is related to function hoisting. As Stoyan Stefanov states in his book JavaScript Patterns, the term hoisting is not defined by ECMAScript; however it is a commonly used term for describing JavaScript's hoisting of variables at the top of the function, regardless of where they are declared within the body. As such, named functions are similarly hoisted, however, anonymous functions implementation is not (while the variable storing it, is).

Callback Pattern

Considering functions are objects, they can be passed in as function parameters. This means that a function, can call back functions passed in as parameters. 

Example below:

function callMe( func ) {
	func();
}
// Call back function
function callBack() {}

// Usage
callMe( callBack );

Callback functions and scoping

In the example above, the function callMe issues a call to func(), within it's body, thus the scope of the func() function is callMe. In cases where the scope of func should be a different object, the bind() method can be used. Browsers not implementing ECMAScript5 should implement the call() method for setting a function's context. The example below relies on ECMAScript5 and above:

function callMe( func, scope ) {
	func.bind( scope )();
}

// Call back function
function callBack() {}

// Usage
callMe( callBack, this );

Note how the example above adds a second parameter 'scope', pointing to the object of context for the function call.

Immediate Function

JavaScript provides the syntax for calling a function right after being defined. Example:

(function( a + b ) {
return a + b;
)( 1, 2 );

Note that immediate functions can have parameters, and return values.

Leave a Reply

Your email address will not be published. Required fields are marked *