Strings Can be Objects

Normally, JavaScript strings are primitive values, created from literals:

   var firstName = "John"    <===typeof x will return string

But strings can also be defined as objects with the keyword new:

   var firstName = new String("John")    <===typeof y will return object

When using the == equality operator, equal strings looks equal, so (x == y) is true because x and y have equal values:

   var x = "John";
   var y = new String("John");

When using the === equality operator, equal strings are not equal, because the === operator expects equality in both type and value. Therefore, (x === y) is false because x and y have different types (string and object).

Worse of all, JavaScript objects cannot be compared. In the example below, (x == y) is false because x and y are different objects although (x == x) is true because it's the same object:

   var x = new String("John");
   var y = new String("John");


Good habit Whatever you do, don't create strings as objects. Not only do strings as objects slow down execution speed, they just cannot be safely compared. The results can produce nasty side effects!
Back Table of Contents Next