Primitive or wrapper object?

JavaScript is a very forgiven language, we can often be very vague when considering the type of a variable. Usually we can think of primitive instances almost as if they were wrapper objects. Still there is a subtle difference, and we'd better be aware of it.

See this variable definition:
var rawStr = "test"; // 1
var objStr = new String("test"); // 2
1. A primitive string is defined.
2. A wrapper object String is defined.

The two variables could be usually considered as identical, still they are not strictly the same:
if(rawStr == objStr) // 1
    console.log("rawStr is a " + typeof(rawStr) + ", objStr is a " + typeof(objStr));
if(rawStr !== objStr) // 2
    console.log("strictly speaking, a string is not equal to an object String");
1. A raw string and a wrapper String containing the same sequence of characters are loosely seen as equal, but the typeof() operator shows that they actually have a different type (string and object).
2. If we strictly compare them, we see that they are actually different.

Same behavior applies to numbers and booleans:
var rawNum = 42;
var objNum = new Number(42);
if(rawNum == objNum)
    console.log("rawNum is a " + typeof(rawNum) + ", objNum is a " + typeof(objNum));
if(rawNum !== objNum)
    console.log("strictly speaking, a number is not equal to an object Number");

No comments:

Post a Comment