I'm going thru the Javascript tutorial on W3Schools.com and came across something that I really don't quite understand. An understandable explanation was not given in the tutorial. So I was hoping someone could explain this to me.
The scenario is this
var x = new String("John")
var y = new String("John")
The following statement is false and I don't know why.
(x == y)
I understand the comparison of types and objects using the "===" operator but the above two statements appear to have the same objects even though (x == y) says otherwise.
String DOES NOT create a primitive string - String() creates a STRING object - which is a factory of sorts for working with strings.
This would work for equality
new String("a").valueOf() == new String("a").valueOf()
Odd they didn't explain this further. It's hard enough to get around the =, == and === operators in JS, no reason to add this oddity as well to that mix!
Code:
"A" == "A"
true
"A" === "A"
true
(new String("A") == new String("A"))
false
(new String("A") === new String("A"))
false
(new String("A").valueOf() === new String("A").valueOf())
true
*** Read the sticky in the DB forum about how to get your question answered quickly!! ***
Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".
Thanks for the explanation and illustrations. I guess the important take-away is to use the "valueOf()" method when assigning/retrieving string values.