JavaScript Undeclared

So how does one determine whether a variable has been declared in JavaScript? I’ve seen two possible methods:

1) Use the in operator:

var x;
alert("x" in this); // alerts: true
alert("y" in this); // alerts: false

2) Use the hasOwnProperty() method of an object:

var x;
alert(this.hasOwnProperty("x")); // alerts: true
alert(this.hasOwnProperty("y")); // alerts: false

What’s the difference between these two? The in operator follows the prototype chain to locate a property, hasOwnProperty() does not:

var o = {};
alert("toString" in o); //alerts: true
alert(o.hasOwnProperty("toString")); //alerts: false

One other small difference is that hasOwnProperty() seems to work on a primitive whereas in does not:

var s = ""; // create a string primitive
alert(s.hasOwnProperty("length")); // alerts: true
alert(s.hasOwnProperty("nope")); // alerts: false
alert("length" in s); // TypeError: invalid "in" operand s

Apparently this is because when you call a method on a primitive it’s temporarily converted to its related Object (e.g., “String”) and discarded afterwards. With the in operator there is no such conversion.

Note: If you’re following these examples, be aware that in IE9 I got “Object doesn’t support this property or method.” when trying to call this.hasOwnProperty() or window.hasOwnProperty() in global context. Any other object should not have this issue.

So while it’s interesting and maybe helpful to know if something has been declared, there’s a big difference between being “declared” and being “defined”. Stay tuned for details on testing whether or not a variable has been defined…

Finally, here’s a few links that were helpful in preparing this post:

Advertisements
This entry was posted in development and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s