ActionScript: Should I always use strict equality ("===")?

900 views Asked by At

I'm wondering if I should always use "===" (strict equality) when doing equality checks... Is there any example of when it is preferable to use "==" (non-strict equality)? In particular, should:

  • if (param1 == null || param1.length == 0)

be

  • if (param1 === null || param1.length === 0) ?

What about with things like strings? param1 == "This is a String."

2

There are 2 answers

0
jpsimons On

I don't actually know much about ActionScript, but I believe it's EMCAScript compliant which means my JavaScript knowledge would be relevant.

In JavaScript, if you're willing to embrace explicit typing (this means never do "something" + 5, always be explicit in your types e.g. "something" + String(5)), if you embrace that approach there's actually never an instance where == is preferred to ===.

0
AdamJonR On

The operator that should be used depends on your needs.

The "==" checks if two values are equal after they've been converted to the same datatype (if possible.) So, "5" == 5 would be true, because the string "5" is converted to a number, and then the check is made, and obviously 5 does in fact equal 5.

The "===" checks if two values are the same type AND equal. So, "5" === 5 would evaluate to false because one is a string and one is a number.

In terms of choice of use, it comes down to expectations. If you expect the two values your comparing to be of the same type, then you should use "===". However, if they can be of different types and and you want the comparison to perform the conversion automatically (e.g., comparing a string 5 to a number 5), then you can use "==".

In the case of your examples, all of them should be fine with the "==" operator, but for added type safety, you certainly can use the "===" operator. I tend to specifically check for nulls, for instance.

Hope this helps.