Tuesday, August 21, 2012

JAVASCRIPT == or ===

In JavaScript we have loosely defined vars so this means that if you have

a = "5"
b = 5

that using (a==5) will return true even though they are not the same var (object) type. This can be annoying and can lead to errors. On the more realistic side who compares strings to ints without first parsing anyway. Well being a loose var system I guess it could happens to anyone. So the solution is to use === which will test for both value and object type to be equal.

Now the question comes up, what about comparing properties in polymorphic objects. At first thought we you might think that === will cause the comparison to fail when comparing two objects that are of different sibling types of a common parent. However this is not an issue as when doing this comparison we are actually only test each var that was extracted from those objects and not the object themselves. In other words the var type of the property becomes the comparable object which requires us to revert to using the === anyways.

So to answer the unanswered question: who compares strings to ints without parsing first well the answer would JavaScript programmers :)

No comments:

Post a Comment