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

Posted October 1, 2009 at 9:05 AM by Ben Nadel

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:

  • 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:

  • <!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:

  • 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:

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




Reader Comments

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


Jan 6, 2012 at 9:17 AM // reply »
2 Comments

Hey Ben, this was just the snippet that I needed. It works a treat mate. thanks.


Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
InVision App - Prototyping Made Beautiful With Prototyping Tools Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
Feb 10, 2012 at 7:21 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
Update! Instead of $(eval(options.insertAfter)).after(data['insertData']); I now use: var ajaxNode = document.createElement('span'); var parent = $(eval(options.insertAfter))[0].parentNode; ... read »
Feb 10, 2012 at 6:18 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
encountered this same, what I consider, jQuery bug last week. I'm building a site in which I load some content via AJAX. This content contains Linkedin share button placeholders which Linkedin API ne ... read »
Feb 10, 2012 at 11:30 AM
Cross-Origin Resource Sharing (CORS) AJAX Requests Between jQuery And Node.js
After you understand the concepts here, this is an awesome cheatsheet for enabling CORS in just about anything http://enable-cors.org/ ... read »
JM
Feb 10, 2012 at 9:10 AM
My Safari Browser SQLite Database Hello World Example
@Amy, Here is a very good tutorial on how to use JOIN: http://www.sqltutorial.org/sqljoin-innerjoin.aspx ... read »
Feb 10, 2012 at 4:42 AM
Building A Twitter-Inspired RESTful API Architecture In ColdFusion
This is great, very useful Ben. I spotted a small typo in the api.cgm listing: <cfthrow type="Unauthroized" /> Cheers Stefan ... read »
Feb 9, 2012 at 10:35 PM
CFDirectory Filtering Uses Pipe Character For Multiple Filters (Thanks Steve Withington)
I was wondering if there would be a filter you could apply so that you got everything but what you included in the filter. As in show me all docs that are not a .pdf. ... read »
Feb 9, 2012 at 10:29 PM
Learning ColdFusion 9: Application-Specific Data Sources
@Ben, No offence, but if people were really wanting advanced features they would be using a platform like ASP.NET MVC. CFML is so structurally compromised as a tag-based scripting language that ... read »
Feb 9, 2012 at 10:03 PM
Subversion - Cleanup Failed To Process The Following Paths
@Leviaguirre, do you still have problems with this? ... read »