Using Javascript's IN Operator To Test For Object Property Existence

Posted October 1, 2009 at 9:05 AM

Tags: Javascript / DHTML

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  |  Other Searches  |  Print Page




Reader Comments

Oct 1, 2009 at 9:25 AM // reply »
10 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 };


Oct 1, 2009 at 9:29 AM // reply »
7,538 Comments

@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.


Oct 1, 2009 at 9:29 AM // reply »
7,538 Comments

@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!


Oct 1, 2009 at 10:15 AM // reply »
3 Comments

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.


Oct 1, 2009 at 10:20 AM // reply »
7,538 Comments

@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?


Oct 1, 2009 at 10:42 AM // reply »
3 Comments

@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.


Oct 1, 2009 at 10:45 AM // reply »
7,538 Comments

@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?


Oct 1, 2009 at 11:03 AM // reply »
10 Comments

@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...


Post Comment  |  Ask Ben

Recent Blog Comments
Mar 18, 2010 at 6:03 AM
ColdFusion Session Management Revisited... User vs. Spider III
Hi Ben, no, the timour is not dynamic at all. The two code chunks are: // This application definition is for robots that do NOT need sessions. this.name = "eClipse_KABS_Boomerang" ... read »
Mar 18, 2010 at 1:25 AM
Ask Ben: Blocking WSDL Access In A ColdFusion Application
Well,I have to say,this is too complicated for me to understand.But I think you're great,keep doing it. ... read »
Mar 17, 2010 at 11:36 PM
Learning ColdFusion 8: CFImage Part I - Reading And Writing Images
@Ben, It is. But I have tested again and sleep() seem to be keeping windows hanging. As a result, multiple people were having issues uploading and removing images when they are trying to do the imag ... read »
Mar 17, 2010 at 11:22 PM
Google Maps Not Working in Internet Explorer (IE)
@James The page has a problem in IE7, because line 112 has a comma at the end. Line 112 is the first problem, there are many more with the same. Ralph ... read »
Mar 17, 2010 at 8:39 PM
Looping Over ColdFusion JSON Queries In jQuery
Thanks Ben - this is just what I needed - just getting up to speed with jQuery - and your posts are accelerating that process substantially :) ... read »
Mar 17, 2010 at 7:50 PM
ColdFusion ArraySplice() Method As An Example Of A Dynamic Method Signature
Java is awesome and I love seeing new twists on it. @Ben - I totally agree with you. ... read »
Mar 17, 2010 at 4:13 PM
Testing For NULL Values In A ColdFusion Query Result Set
To get around the empty strings in an UPDATE statement I pretended the variable was a string by enclosing it in single quotes, CAST it to an integer, let it convert empty strings to zeroes, and used ... read »
Mar 17, 2010 at 4:12 PM
Ask Ben: Environment-Based Application.cfc Settings
Ben, those are valid comments. I posted some code that shows how to "worryfree ;o)" copy code and let the Application.cfc sort it out. http://boncode.blogspot.com/2010/03/cf-dynamically-changing-ap ... read »