Javascript Snippets

Programming in Javascript is generally quite a breeze! But, there’s some things that are worth adding to a snippet archive because they’re extremely useful and perhaps not immediately obvious.

Global nature of Javascript

Sometimes global is useful – i.e. when you’re hacking. If your developing a useful and extensible app however, you want things to be modular and in particular encapsulated. To encapsulate and prevent contaminating the global namespace of Javascript (which has no such dedicated thing as a namespace as such) we use the Pattern.

Object.defineProperty( Object.prototype, "has", { value: function( needle ) {
    var obj = this;
    var needles = needle.split( "." );
    for( var i = 0; i<needles.length; i++ ) {
        if( !obj.hasOwnProperty(needles[i])) {
            return false;
        obj = obj[needles[i]];
    return true;

String formatting

The String prototype doesn’t include a format() method which is a shame. I prefer to write a formatted string followed by a list of the format values as I can then decipher the string easier. It’s a lot easier for a translator to understand a formatted string rather than a broken set of words. It’s the difference between:

var str = "I've found {0} of a possible {10} solutions".format( 1, 10 );


var str = "I've found " + 1 + " of a possible " + 10 + " solutions";

Here, like the above Object.defineProperty option, we can extend a strings prototype more easily to include a fomat like option. Although it doesn’t include (m)any formatting options it generally doesn’t need to because Javascript is very good at converting objects to strings implicitly anyway:

String.prototype.format = String.prototype.f = function() {
    var s = this,
        i = arguments.length;

    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    return s;

Leave a Reply