← Back to Upcase

Variable comparison woes


(Jon Seidel) #1

I’m working up some Javascript and testing with Jasmine, but one comparison has me stumped. Here’s my spec:

it("returns true when the strings are simple permutations", function() {
  var xStrings = new xStrings();
  expect(xStrings.is_permutation('a','a').toBe(true);
}

and the code under spec is:

xStrings.prototype.is_permuation = function(string1, string2) {
  var s1 = new String(string1);
  var s2 = new String(string2);
  if(string1 == string2) {
    return true;
  }


After a little trial and error, I found that the following comparison works as I expected the original one to work.

if(string1.valueOf() == string2.valueOf())

Why is this? I thought that the == comparison did an ‘intelligent’ conversion of data values?


(Joel Quenneville) #2

Any reason that you are wrapping string1 and string2 in String objects? == compares String objects by identity rather than by value.


(Jon Seidel) #3

Thanks, @joelq. I was using the String objects because I figured it would be best to just make them objects in advance so that I could use the object methods without invoking the conversion overhead to go from primitive to object. However, the SO answer here puts the kibosh to that, so I’m switching back to primitives.

Regarding the difference between == and ===, my understanding is that === is the ‘strict’ euality comparison and requires that the types match (what you might call the ‘identity’ comparator?), whereas == is the ‘lenient’ equality comparison which attempts to convert non type-equal operands before it does the comparison. The SO answer here has a great discussion about the two.