As explained in the post "Javascript Classes", javascript objects inherits properties and methods from its prototype objects. Due to this behavior is possible to extend a native object by adding custom properties to its  prototype object.

In Javascript is available the "String" native object which wrap the "string" primitive data-type and provides a number of helper methods (charAt(), indexOf(), slice(), split(), replace(), ...).

Lets see how to extend this native object with the "paddingLeft" and "paddingRight" functionalities:

// padding left
String.prototype.padLeft = function (paddingChar, length) {

var s = new String(this);

if ((this.length < length) && (paddingChar.toString().length > 0))
{           
    for (var i = 0; i < (length - this.length) ; i++)
    s = paddingChar.toString().charAt(0).concat(s);
}

return s;
};

// padding right
String.prototype.padRight = function (paddingChar, length) {

var s = new String(this);

if ((this.length < length) && (paddingChar.toString().length > 0)) {
    for (var i = 0; i < (length - this.length) ; i++)
    s = s.concat(paddingChar.toString().charAt(0));
}

return s;
};

Now we can use elsewhere in our code the new methods:

var n = 123;
var s = n.toString().padLeft("0", 5); // s="00123"