Why does the following statement return false in JavaScript?
new String('hello') === new String('hello')
Because == (and === ) test to see if two objects are the same object and not if they are identical objects.
new String("text"); explicitly creates a new and referentially distinct instance of a String object; String s = "text"; may reuse an instance from the string constant pool if one is available.
String strLiteral = "Java"; Both expressions give you a String object, but there is a subtle difference between them. When you create a String object using the new() operator, it always creates a new object in heap memory.
So === faster than == in Javascript === compares if the values and the types are the same. == compares if the values are the same, but it also does type conversions in the comparison. Those type conversions make == slower than ===.
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.
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')
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With