Using Jquery Deferred

I am going to give a simple example which would explains the usage of Jquery deferred concept. The Jquery deferred plays a vital role in handling asynchronous actions. The $.Deferred is used internally by many Jquery API such as ajax and animations.

The $.Deferred usage flow will be as follows.

  1. Instantiate deferred object using $.Deferrred() when some action starts.
  2. When the action completed, resolve the deferred object using resolveWith/rejectWith and your parameter.
  3. Return the promise object from the function for chaining ability

Now I am going to explain using $.Deferred object with the simple animation operation.

For that we have a HTML element as follows.

<input type="button" value="Animate" />
<div id="target" style="border: solid 1px black; width: 500px; height: 70px;"></div>

And the function which will perform the animation is as follows. The below function will animate the width of the div element from 500px to 10px. I had not written the animate function in a generic way as I am going to concentrate on using deferred promise.

    function animate() {

            //Initialize Deferred object.
            var deffered = $.Deferred();   Step 1

            width = +$("#target").outerWidth();

            var inter = setInterval(function () {
                $("#target").width(width-- + "px");

                //Stops animation when width reaches 10.
                if (width == 10) {


                    //RESOLVE THE DEFERRED WITH arguments.
          Step 2 deffered.resolveWith($("#Grid"), [{ width: width }]);

            }, 10);
            //Returns promise object to chain operation.
         Step 3   return deffered.promise();

Now the animation function can be invoked as follows. And when the animation completed, the promise object will get resolved and call the corresponding callback registered using done. If fails, the callback registered with fail will be invoked.

       //Input element click handler.
        function change() {            

            animate().done(function (e) {
                console.log(e.width); //Returns 10


And I said in the Step 3 to return the promise object. But we should be careful in using this since it sometimes led to anti-pattern.

Monkey patching

Monkey patching is a technique that uses the flexibility of the JavaScript to modify any function/method behavior.

Performing monkey patching is simple and it can be done by the following steps.

  1. Store the original function in a variable
  2. Now modify the function behavior
  3. Call the original function using apply.

This can be useful when you want to change the argument values of the function. For example, consider we have the following class.


        var math = function () {
            this.a = 1;
            this.b = 2;

        math.prototype = {
            sum: function (a, b) {
                return a + b;

Now we can modify the method sum using the monkey patching technique as follows.

        var original = math.prototype.sum;   Step 1

        math.prototype.sum = function (a, b) {
            a = a * 2, b = b * 2;    Step 2

            return original.apply(this, [a, b]);    Step 3

On executing the above method, the result will as follows.

       var obj = new math();

        obj.sum(1, 2); //return 6;
        //Expected: 3, Actual : 6 due to monkey patch

Happy Scripting… 🙂

Using JSON parse and stringify methods

JSON plays vital role in JavaScript when comes with server interaction. But i noticed when people spoke about JSON they represent it as JSON object in Javascript which is incorrect. JSON is not a object it is just a string format which can be converted to object/array based on its language(Javascript, C#, C++ etc.)

JSON can be converted to JavaScript object using JSON.parse and JSON.stringify vice verse.


It is similar to the serialization of the object. The signature of the stringify method is as follows.

JSON.stringify(value[, replacer[, space]])

In the above the first argument is the object/array to be converted to JSON formatted string.

Controlling the stringify operation

Using replacer

The second argument of the stringify method is the replacer which can be an array or function and the value returned from the replacer will be stringify.

Example 1: using array

JSON.stringify({ a:1, b:2, c:null }, ["a","c"]);
//Output: "{"a":1,"c":null}"

Example 2: using function

JSON.stringify({a:1,b:2,c:null}, function(key, value) { return value != null ? value: undefined });
//Output: "{"a":1,"b":2}"
Using toJSON property

It is an another way of customizing the stringify operation. If an object contains a property named toJSON then the value returned from this function will be stringified instead of whole object.

var exFn = function() {
                      this._sum= function() { return this.a + this.b };
                      this.toJSON = function() {
                                             return {
                                                      b: this.b,
                                                      sum: this._sum()
//Output: JSON.stringify(new exFn())


It is similar to the de-serialization of the object. The signature of the parse method is as follows.

JSON.parse(text[, reviver])

In the above the first argument is the JSON text input which has to be parsed to JavaScript object/array. For that the JSON string must abide the standards provided by the ECMA-404 The JSON Data Interchange Standard.

Controlling the parse operation

The parse operation can be controlled using the second argument of the parse method. It can be of type function. If the reviver is used then the parse will be done only based on the value returned by the reviver if reviver return undefined then that key will be excluded. The below will exclude the key with null values

var d = "{\"a\":1,\"b\":1,\"c\":null}"
JSON.parse(d, function(key, value){ if(value) return value; });
//Output: Object { a=1,  b=1}

Simple type casting in Javascript

This is my first blog for my very favorite language.

JavaScript is a very flexible language that would make to do many magical things. But the programming this language should be done careful since every browser is running in a single thread.

Type casting in JavaScript


We all know the string or date can be converted to number using parseInt/parseFloat. But we can also use the “+” operator to do the same.

var d = +"43" //43

var d = +"4.3" //4.3

var d = +"4e" //NaN

var d = +new Date() //returns date value in milliseconds.


ToString method can be used to convert any number, boolean or date to string value. But it can be more simple by using the concatenating a “” at the end.

var d = 4 + "" //"4"

var d = new Date() + "" //"Wed Jul 22 2015 15:40:26 GMT+0530 (India Standard Time)"

String to Boolean

There is no simple way to cast from “true” string value to true boolean type. We have to do as follows.

var d = val == "true" ? true : val == "false" : false;