Why does new String('hello') === new String('hello') evaluate to False? [duplicate]
Solution 1:
Two String objects will always be unequal to each other. Note that JavaScript has string primitive values as well as a String constructor to create wrapper objects. All object equality comparisons (especially with ===
) are carried out as a test for reference equality. References to two different objects will of course never be equal to each other.
So "hello" === "hello"
will be true
because those are string primitives.
Solution 2:
You are comparing object instances, which is not like a string comparison ('hello' === 'hello'
) Comparing objects in Javascript is actually comparing the memory addresses of the objects and will always return false because memory addresses are different for each object.
Compare the string values instead of the object instance - jsFiddle
( String('hello') === String('hello') ) // returns true due to comparing strings
Strictly comparing two objects - false not the same object
new String('hello') === new String('hello')
Strictly comparing two strings - true, same returned value and same returned type
String('hello') === String('hello')
Solution 3:
It evaluates to false because you're comparing two different objects: new will create a new object.
Related post: What is the 'new' keyword in JavaScript? Which explains in its (extensive) answer:
It [new] is 4 things:
- It creates a new object. The type of this object, is simply object.
- It sets this new object's internal, inaccessible, [[prototype]] property to be the constructor function's external, accessible, prototype object (every function object automatically has a prototype property).
- It executes the constructor function, using the newly created object whenever
this
is mentioned.- It returns the newly created object, unless the constructor function returns a non-primitive value. In this case, that non-primitive value will be returned.