What is this code construct wrapping the parts of a library and what is it useful for?

It’s a module pattern. You’ll see many variants of that pattern, so it’s essential to understand what really happens, you can’t just imitate one.

The point of this piece of code is to complete an object c (typically your global library). You probably have many similar pieces of code in your application, all building pieces of c, probably each of those in its own file.

In case the library object c, which is passed as argument to the function, doesn’t exist yet ( c === undefined ), it is created. This makes it possible to not depend of the execution order or of a preexecuted file.

The right part of the assignment is an IIFE (Immediately Invoked Function Expression), that is a function which is immediately called. The advantage of this construction is that it creates a scope in which variables (for example the a function) can be declared without polluting the external (global) scope. Here the point is moot as a is externalized anyway but a module typically depends on several internal (private) functions and variables.

A detail that might need an explanation : all those files look like they define a new variable c but there’s no problem here, even if the files are concatenated : a var statements doesn’t define a new variable if it already exists (a variable is defined for the whole scope, here globally, even before the point of declaration).

Another way to write this would have been

var c = c || {}; // ensure the c variable is defined, and initialize its value it if necessary

(function() { // let's use an IIFE to have a protected scope and not pollute the global one
  function a() {
  c.a = a; // let's augment c

This one is probably clearer as

  • it explicitly separates the two steps (c initialization and c completion using an IIFE)
  • it doesn’t depend on two c variables with the same name
  • it is less verbose

Leave a Comment