The in operator

Published Thu, Aug 27 2009 10:13

Even though you’ve might have been writing JavaScript code for some time, chances are that you haven’t heard about the in operator. However, this changes when you’re asked about the for( … in …). The fact is that most people know that there’s a for(… in …) statement but don’t know that you can use the in operator outside a for loop.

What does this operator do? It will simply check if an object has a specific property. Here’s a really simple example which checks if an object supports the “name” property:

var User = function(name, age) { 
    this.name = name;
    this.age = age;
}
var propName = "name";
var user = new User("luis", "33");
alert( propName in user);

The in operator expects two operands: on the left side, it expects a string or a numeric expression which will be checked against the object present on its right side. You can also apply this operator with arrays. However, in this case you’ll only be able to check supported indexes. Here’s an example:

var names = ["luis", "john", "peter"];
alert("peter" in names);//false
alert(2 in names);//true

Here’s a resume of what this operator returns:

  • false for a non existing property or for a property which has been deleted (don’t forget that we can remove properties from an object through the delete operator);
  • true for existing properties, even though those properties might have been set to undefined.

You’re probably wondering if this operator is that important. I confess that I haven’t used it much, but I do find it useful in certain scenarios. For instance, Douglas Crockford has used it in his helper functions that support classical inheritance.

Filed under:

Comments

# Mikael Söderström said on Thursday, August 27, 2009 5:02 AM

This can be great to use while unit testing JavaScripts to see if the required methods exists.

# Bertrand Le Roy said on Thursday, August 27, 2009 3:39 PM

Wow. How did I not know that? :)

Would be interesting to show the differences with hasOwnProperty.

# LA.NET [EN] said on Friday, August 28, 2009 3:42 AM

In yesterday’s post about the in operator, Bertrand mentioned that it would be interesting to show the

# ASPInsiders said on Friday, August 28, 2009 4:12 AM

In yesterday’s post about the in operator, Bertrand mentioned that it would be interesting to show the

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above:  

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Silverlight 4.0: Curso Completo

    ASP.NET 4.0: Curso Completo

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover