How do I check whether a property exists, without generating runtime warnings?
(Adapted from email by P. T. Withington to laszlo-dev)
The 'correct' way to ask if a property exists is the `in` operator
if ('bar' in foo)
If you want know that the property is an immediate property (not inherited from the superclass) then you can ask:
The compiler currently does not warn if you ask for a non-existent property using the index operator:
but as Adam Wolff has said, that is a bad idiom that we ought to purge. The whole point of the 'undefined' warnings is to help you debug your code. Someday we will need to turn on warnings for that (and have a whole raft more warnings to clean up). This is captured in a bug at LPP-2030
We also should distinguish between a non-existent property and a property whose value is `undefined`. In earlier swf runtimes, this was not possible, but we could do that now. This is also captured in a bug LPP-2031
The compiler will also not warn for a non-existent property if you take `typeof` an non-existent property, so this test:
if (typeof foo.bar != 'undefined')
is another way to check. The intent is that you would not just check that the property was defined, but check that it is of the correct type. Since you are checking, any warning would be superfluous.
By extension, the compiler ought not warn if you ask `foo.bar instanceof <class>`, or as you suggest `foo.bar == void 0`. But that just creates more idioms we will eventually need to fix. I suggest we stick with the two idioms we have for now and elevate the priority of LPP-969.
See this blog entry for why I say `void 0` rather than `undefined`.