One of the great advantages of some languages, such as JavaScript and Ruby, is the ability to ‘monkey-patch’ or extending the built-in classes. Often it is used to the extend built-in types, this has the great advantage of allowing us to call methods of objects in the native format object.method(). I’ve often found it frustrating that JavaScript doesn’t offer a ‘contains()’ method for strings, this is easy enough to fix with some patching:

//Check to ensure that the method doesn't exist
if(typeof String.prototype.contains !== 'function')
{
 //I'm going to add a method to the String object's prototype
 String.prototype.contains = function (s)
 {
//indexOf(s) returns -1 if the given string (s) does not exist in the string it's called against.
if(this.indexOf(s) != -1){ return true; }else{ return false; }
 };
}

Now I have a method called ‘contains’ on all of my strings, which means that I can call it like

var foo = "Hello World!";
if(foo.contains("Goodbye"))
{
 alert("ByeBye");
}

This has some advantages, mostly just readability, but it also comes with some drawbacks. If you are using an external library you may be changing the functionality that the library expects. This makes the need for

if(typeof String.prototype.contains !== 'function')

an absolute must, however if the library plays nicely you may still be changing it expected behaviour. I have a few others that I frequently include in my standard library:

if(typeof String.prototype.contains !== 'function')
{
 String.prototype.contains = function (s){
if(this.indexOf(s) != -1){ return true; }else{ return false; }
 };
}

if(typeof String.prototype.trimLeft !== 'function')
{
 String.prototype.trimLeft = function ()
 {
return this.replace(/^\s*?[^\s]/img, '$1');
 };
}

if(typeof String.prototype.trimRight !== 'function')
{
 String.prototype.trimRight = function ()
 {
return this.replace(/[^\s]\s*?$/img, '$1');
 };
}

if(typeof String.prototype.trim !== 'function')
{
 String.prototype.trim = function ()
 {
return this.trimLeft().trimRight();
 };
}

//These two are good for some Google Maps work.
if (typeof Number.prototype.toRad !== 'function')
{
 Number.prototype.toRad = function ()
 {
return this * Math.PI / 180;
 }
}
if (typeof Number.prototype.toDeg !== 'function')
{
 Number.prototype.toDeg = function ()
 {
return this / Math.PI * 180;
 }
}