Some javascript design patterns I use

13 Jul, 2013 05:07 AM
 javascript
 pattern
I have been coding in javascript intensively for a year now and here are some of the patterns that i have begun to internalize.

Avoiding conflicts in global namespace

While I'm consuming plenty of javascript libraries in my web application, my own javascript might inadvertently conflict with variables and functions defined in global namespace by the included libraries. While I don't want to fiddle with a library, i have to correct my own behaviour here - avoid writing into global namespace.

One of the best pattern I use to do this is to create an anonymous function that is invoked immediately and just move my entire javascript into this - 

 Avoiding global namespace - Example
(function() {
  var a; //This has the enclosing anonymous function scope
  function doSomething() {
    alert(a); //Variable 'a' is available in this scope
  }
  doSomething();
})()


Object Orientation

I love to encapsulate my code - information hiding and scoping. The one way i love to do it is using the object literal syntax - 

Object Orientation - Example
function Car() {
  var color = 'RED';
  function getColor() {
    return color;
  } 
  return {
    getColor : getColor
  }
}

var car = Car();
console.log(car.getColor());

There are several variants to the above pattern but all return a closured object using literal syntax. I prefer the above over the prototype pattern - 

Object Orientation - Example (Not Preferred)
function Car() {
  this.color = 'RED'; //Variable 'color' is in public scope
}

var car = new Car();
console.log(car.color); //Variable 'color' is accessible outside
 

Currying

The beauty of javascript lies in the closure and anonymous function. I can use these paradigms and pass blocks of code around. Let us say i want to show an alert after 5 seconds. I use the setTimeout built-in function but it only accepts function references. This wont work!

Alert after 5 seconds - Example (wont work!)
setTimeout(alert('Timed out!'), 5000);

Correcting it - this works -

Alert after 5 seconds - Example 
setTimeout(function() {
  alert('Timed out!')
}, 5000);

Much better with currying -

Currying - Example 
function warnAfter(seconds) {
  return function() {
    setTimeout(function() {
      alert('Timed out!')
    }, seconds * 1000);
  }
}
setTimeout(warnAfter(5), 5000);
setTimeout(warnAfter(10), 5000);

Adios!