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 »
11,314 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 »
11,314 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 »
11,314 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 »
11,314 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 »
3 Comments

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


May 2, 2012 at 12:47 PM // reply »
2 Comments

Nice post! As you have discussed above , i agree everything you say. I know that IN operator is used to identify the object .I know that the JavaScript is a powerful tool which is used to provide a action in our website as well as submit the form .It uses all the oops concept except the inheritance.
Thanking you.


May 2, 2012 at 12:47 PM // reply »
2 Comments

Nice post! As you have discussed above , i agree everything you say. I know that IN operator is used to identify the object .I know that the JavaScript is a powerful tool which is used to provide a action in our website as well as submit the form .It uses all the oops concept except the inheritance.
Thanking you.


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
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
Jun 19, 2013 at 9:38 PM
Directive Link, $observe, And $watch Functions Execute Inside An AngularJS Context
@Alesei, Glad you like it. Even after working with AngularJS for months, I still get a bunch of unexpected, "$digest is already in progress". So hard to debug sometimes! ... read »
Jun 19, 2013 at 9:36 PM
Working With Inherited Collections In AngularJS
@Mike, The relationship of $scope values is definitely an interesting thing! But it's not simple - it really forces you to understand prototypal inheritance, which is not at all a simple topic! Gla ... read »
Jun 19, 2013 at 9:35 PM
Experimenting With The Amazon Simple Storage Service (S3) API Using ColdFusion
@Joe, Oh, super interesting! I had only thought to url-encode the signature; but I think that's because the S3 docs actually have a special NOTE telling you to do so. It would have never occurred t ... read »
Jun 19, 2013 at 9:32 PM
Experimenting With The Amazon Simple Storage Service (S3) API Using ColdFusion
@Richard, Glad you like! Hopefully I'll have some more interesting stuff coming. This morning, I blogged a bit more about generating the pre-signed, query string authenticated URLs; but, then deeme ... read »
Jun 19, 2013 at 9:31 PM
Filter vs. ngHide With ngRepeat In AngularJS
@Mike, Honestly, in the majority of cases, I would say there isn't going to be a difference. Both approaches have trade-offs. If you use the filter, then you have fewer DOM elements and fewer $scop ... read »
Jun 19, 2013 at 2:01 PM
Experimenting With The Amazon Simple Storage Service (S3) API Using ColdFusion
I have coincidentally been beating my head against the S3 API for the last week or so. One big "gotcha" I had to work around was file names and paths containing spaces. Remember to URL Enco ... read »
Jun 19, 2013 at 1:27 PM
Using Slice(), Substring(), And Substr() In Javascript
very good article. By the way IE supports negative values in substr or slice in verson 10. ... read »
Jun 19, 2013 at 11:33 AM
Filter vs. ngHide With ngRepeat In AngularJS
In your assessment, is it correct to say that given a list of say 500 items its more performant to use the `ngHide` method over the `filter` method? ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools