Using Javascript's IN Operator To Test For Object Property Existence
Posted October 1, 2009 at 9:05 AM
A small, but powerful tip that I picked up while reading Cody Lindley's jQuery Enlightenment book, was the use of Javascript's IN operator to test for object property existence. Before that, I had only ever used the IN operator to iterate over an object's keys, as in:
Launch code in new window » Download code as text file »
- for (var key in myObject){
- // ... key is iteration index value ...
- }
To be honest, I didn't even know that it could be used in any other way; but apparently, it can be used to check to see if a given key exists in a given object (or index in a given array). While this might seem rather insignificant, there are already cases that I have found it to be very useful. Specifically, cases where you need to check if a key exists in an object and the value of that key might be a "falsy" (a value that can be implicit cast to a false Boolean). To see how this can be used, take a look at this example:
Launch code in new window » Download code as text file »
- <!DOCTYPE html>
- <html>
- <head>
- <title>Javascript's IN Operator For Testing Property Existence</title>
- <script type="text/javascript" src="jquery-1.3.2.js"></script>
- </head>
- <body>
-
- <h1>
- Javascript's IN Operator For Testing Property Existence
- </h1>
-
- <script type="text/javascript">
-
- // Create a new object to contain our properties.
- var jill = {
- blonde: false,
- brunette: true,
- sexy: true,
- funny: true,
- plump: false,
- "short": true,
- sassy: null
- };
-
- // Create an array of keys that we will want to check for
- // in the given struct.
- var keys = [
- "angry", "blonde", "brunette", "sexy", "funny",
- "plump", "short", "tall", "sassy"
- ];
-
-
- // Iterate over the key collection and only output the
- // keys that are in the given object.
- $.each(
- keys,
- function( index, key ){
- // Check to see if this key exists using simple
- // array notation.
- if (jill[ key ]){
-
- document.write(
- "Key [ " + key + " ]: " +
- jill[ key ] +
- "<br />"
- );
-
- }
- }
- );
-
-
- document.write( "- - - - - - - - <br />" );
-
-
- // This time, we will iterate over the keys in the
- // collection, but check for key existence using
- // Javascript's IN operator.
- $.each(
- keys,
- function( index, key ){
- // Check to see if this key exists using
- // javascript's IN operator.
- if (key in jill){
-
- document.write(
- "Key [ " + key + " ]: " +
- jill[ key ] +
- "<br />"
- );
-
- }
- }
- );
-
- </script>
-
- </body>
- </html>
In this demo, we have an object that has keys (properties); some of the values located at these keys are True and some are False and one is NULL. Checking for the existence of a given key can cause an "unexpected" result if the corresponding value is False or NULL (NOTE: By "unexpected," I simply mean unintended, not technically wrong). As such, when we run the above code, we get the following output:
Key [ brunette ]: true
Key [ sexy ]: true
Key [ funny ]: true
Key [ short ]: true
- - - - - - - -
Key [ blonde ]: false
Key [ brunette ]: true
Key [ sexy ]: true
Key [ funny ]: true
Key [ plump ]: false
Key [ short ]: true
Key [ sassy ]: null
As you can see, if we check for a given key using basic array notation:
Launch code in new window » Download code as text file »
- if (jill[ key ]){ .... }
... then only keys that exist AND have a corresponding "truthy" value will be used. However, if we use Javascript's IN operator to test for key existence:
Launch code in new window » Download code as text file »
- if (key in jill){ .... }
... then only the key itself is tested, and the truthy / falsy nature of the corresponding value is not even taken into account.
I love when I read a book, like jQuery Enlightenment, and just come away with a bunch of little gems like this. It might seem like a small, insignificant tip; but the moment you need to do something just like this, knowing how to properly test for key existence makes all the difference.
Download Code Snippet ZIP File
Post Comment | Ask Ben | Permalink | Other Searches | Print Page
Newer Post
jQuery's is() Method Checks For Any Matching Elements
Older Post
Parsing Invalid HTML Into XML Using ColdFusion, Groovy, And TagSoup
Reader Comments
Nice tip Ben! The "in" operator is definitely good to know about.
The reason that your first example only spits out "truthy" values is because this:
if (jill[ key ]){ .... }
... is essentially the same as this:
if (jill[ key ] == true){ .... }
(Notice the NON-strict equality operator)
If you try retrieving a property that doesn't exist then "undefined" should be returned, which can be tested in the following way:
if (jill[ key ] !== undefined){ .... }
Unfortunately, "undefined" can be re-defined (I believe this is fixed in ES5), so it's safer to test using the typeof operator:
if (typeof jill[ key ] !== "undefined"){ .... }
There are still advantages to your "in" method though - for one, it will work even when a property is "undefined", e.g.
var someObject = { foo: undefined };
@James,
Yeah, exactly; there's not "technically" wrong with how the evaluation is working - it simply might not be what someone is tending to do.
The IN operator syntax just seems to concise and to the point. And, it reads really nicely.
@James,
Also, I am sure you saw this, but you are on the top blogs to follow for jQuery:
http://www.webresourcesdepot.com/15-blogs-to-follow-for-jquery-lovers/
Rock on with your bad self!
Ben,
While using for in, to truly check that the property is from the current object and not from the prototype chain, you have to use the hasOwnProperty method. No necessary in your above example though.
@Raj,
I do not think that is accurate (unless I am misunderstanding you). Take a look at this code:
function A(){ this.a = true; }
function B(){ this.b = true; }
B.prototype = new A();
var instance = new B();
document.write( "a" in instance );
document.write( "<br />" );
document.write( "b" in instance );
Here, class B extends class A. And, when we check for both "a" and "b" in the concrete class, we get:
true
true
... it looks like it worked regardless of prototypal inheritance?
@Ben,
That's exactly my point. Sometimes, you may not want document.write( "a" in instance ); be true.
The following line will return false, since property "a" is not in B.
document.write(instance.hasOwnProperty("a"));
Sorry if I confused you.
@Raj,
Ahh, I see what you're saying. I have never though of that (testing the specific level of inheritance). Is the hasOwnProperty() method fully cross-browser compliant? Or is that a Mozilla thing?
@Ben, thanks for the heads up on that list! You should have been on there! :)
Also, AFAIK, hasOwnProperty() is supported just about everywhere, except Safari 2. Though, I don't think anyone uses that browser any more...



