Ben Nadel
On User Experience (UX) Design, JavaScript, ColdFusion, Node.js, Life, and Love.
I am the chief technical officer at InVision App, Inc - a prototyping and collaboration platform for designers, built by designers. I also rock out in JavaScript and ColdFusion 24x7.
Meanwhile on Twitter
Loading latest tweet...
Ben Nadel at cf.Objective() 2009 (Minneapolis, MN) with:

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

By Ben Nadel on

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

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 };

Reply to this Comment

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

Reply to this Comment

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.

Reply to this Comment

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

Reply to this Comment

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

Reply to this Comment

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

Reply to this Comment

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

Reply to this Comment

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.

Reply to this Comment

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.

Reply to this Comment

Post A Comment

?
You — Get Out Of My Dreams, Get Into My Comments
Live in the Now
Oops!
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.