Some alternative use of bit wise operators

In this blog, I am just going to share some of the alternative use of the bitwise operators.

1. Replace Math.floor with double ~~.
Even though JavaScript Math library is well optimized, we can use the bitwise operators to reduce some keystrokes.

~~3.4 //result : 3

2. Convert to Boolean using !!
Double NOT operator is used to convert any type into Boolean.

var d = "Hi";
!!d //result : true
var f = null;
!!f //result : false

3. Swap values without temp variable using XOR.
It is the one of the common method used to swap two variables without using temp variable.

var a = 5, b= 6;
a ^= b; b ^= a; a ^= b; //result a = 6, b = 5;

4. Using left and right shift with 1 bit to perform multiply and division.
Left shifting a number 1 bit is equivalent to the result obtained by multiplying it by 2 and right shifting 1 bit is equivalent to dividing it by 2.

var d = 4, f = 6;
d >> 1 //result : 4 * 2 = 8
f << 1 //result : 6 / 2 = 3

5. Checking odd/even using AND with 1
Performing AND operation with 1 will return value greater than 0 if its odd. We can use it simply to find whether a number is odd or even.

var a = 5, b= 6;
a & 1//result 1 - odd
b & 1//result 0 - even

Happy Scripting…


Deserialize JSON to instance of JavaScript class

Prototypical class is used to create classes in JavaScript like other programming languages.
The object return from these classes will have corresponding class information. When you to try to serialize and de-serialize this object, the class information associated with the corresponding object will be removed.

In this post, we are going to see how to retrieve this class information and make the object as the instanceof corresponding class.

The process involves two steps. They are

1. Parse using JSON.parse method.
2. Assign the constructor of the actual class to the __proto__ property of the parse JSON.

Let us see this in details.

If we have a JavaScript class like below.

 var myClass = function(){
this.a = 1;
return this.a;

var d = new myClass(); //result: &amp;quot;{a:1}&amp;quot;;

d instanceof myClass //result: true;

In the above all works fine. The problem will arise if we try to check instanceof on the object from deserialization like shown below.

var str = JSON.stringify(d);

var d = JSON.parse(str); //result: &amp;quot;{a:1}
d instanceof myClass //result: false;

So now d lost its class information and hence it failed. Now we can use the below utility function to retrieve the class information.

var toCalss = function(obj, proto) {
obj.__proto__ = proto;
return obj;

var res = toClass(d, myClass.prototype);

res instanceof myCalss //result: true;

Now the object will have class information which makes the instanceof to work as expected.
Happy scripting..


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;