The in operator
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.