Why new keyword should be used while instantiating JavaScript class

The new keyword is used to instantiate prototypical class or other objects. But why we need new keyword to initialize it, when you to try to initialize it without new will not throw any error at all then why should I use new before my class to instantiate it.

The answer is simple new keyword will set the ‘this’ to the new object created using function instead of global scope”.

If you didn’t provided new keyword then the context will be set to window(global scope).

You can see the difference in the below code example.

var fn = function (){
       this.a = 2;
       return this;
}

Instantiating fn without new keyword.

 var f = fn();  //`this` refers window here.

Instantiating fn with new keyword.

 var f = new fn();  //`this` refer object created by `fn` here.

Even though using new keyword is the best practice to instantiate class, most of the time, the users will skip them as it doesn’t provide any error at all.

We can use the below simple workaround to enforce the instantiating process using new keyword. Then the above fn will become as below.

 var fn = function (){
       if(!(this instanceof fn)) //workaround to resolve this problem.
          return new fn();
       this.a = 2;
       return this;
}

Now instantiating without new will also set this to the current object.

 var f = fn();  //this refer to fn here.

Instantiating class/function without new keyword in ES6 will throw TypeError.

Happy Scripting… 🙂

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..