This question already has an answer here:
Why does the following statement return false in JavaScript?
new String('hello') === new String('hello')
This question already has an answer here:
Why does the following statement return false in JavaScript?
new String('hello') === new String('hello')
Your code essentially says "Take a piece of paper and write 'hello' on it. Take another piece of paper and write 'hello' on that. Are they the same piece of paper?"
Any "object" structure in the "Heap" is unique;
Heap vs. Stack
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 betrue
because those are string primitives.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:
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
Strictly comparing two objects - false not the same object
Strictly comparing two strings - true, same returned value and same returned type
You are asking javascript to compare two different instances of the variable, not the string value that lives inside the variable.
So for example, lets say I have a piece of paper with the word "Hello World" written on it (Paper1) and my brother has a different piece of paper with the word "Hello World" written on it (Paper2).
When you say is Paper1 === Paper2 you will get false, beacuse no they are not the exact same piece of paper, even though the words written on the paper are the same.
If you where to say Paper1.toString() === Paper2 .toString() you would get true, beacuse we are comparing the words written on the paper, not the actual paper itself.