Weird JS
As you know sometimes JavaScript can be weird. Let’s see the following example and let’s try to answer the question: does “undefined” equals “undefined”. What do I mean?
First take a look at the following code.
var a; var b = undefined; // alerts "false" alert(b == a); |
Both a and b are undefined, but they are NOT equal. Now let’s see where it can become a problem.
We have an object with one member variable that is not defined.
var f1 = function() { this.myvar; }; var obj1 = new f1(); |
Now you’d like to know whether the object “b” has the property “myvar”. There are lots of examples online, but what’s the right way?
Wrong
Appearantly the value of b.myvar should be undefined.
alert(obj1.myvar); // undefined |
But that doesn’t mean that it is the same value if the object was declared this way:
var f2 = function() { this.myvar = undefined; }; var obj2 = new f2(); |
This is a completely different thing. Why? In the first case if we try to check whether the property myvar belongs to obj1 we can go wrong with:
if (obj1.myvar) // false |
This is false simply because obj1.myvar is undefined
if (obj2.myvar) // false |
Again is false, because obj2.myvar is undefined.
The same thing happen when using the other “famous” approach.
if (typeof obj1['myvar'] != 'undefined') // false if (typeof obj2['myvar'] != 'undefined') // false |
Clearly this is not the right answer, becase even it is undefined myvar belongs to obj2!
Right
Now let’s try with hasOwnProperty supported by almost every modern browser.
if (obj1.hasOwnProperty('myvar')); // false if (obj2.hasOwnProperty('myvar')); // true |
Here you can see that when the member variable is explicitly defined as “undefined” the object “has the property” and hasOwnProperty returns true. Yet again, “undefined” does not always equal to “undefined”.
Triple equal operator for strict comparison.
a === b; // true
@Jason Mulligan – wrong, again “false”
Chrome says otherwise; see the url for a screenshot.
http://farm7.static.flickr.com/6104/6265793463_b721bf4ea5_o.png
It’s great that Chrome returns true, but if that’s not the case at the other “modern” browsers, then what?
Actually you’re right somehow! When I test it with the Firebug console …
… it strangely returns true.
But within a <script> tag …
is FALSE. Isn’t it weird?
When it runs in firebug console, it alert false. Use console.log(a), it return [a, ,a …]. Here a means the HTMLLinkElements collections