SlightlyLoony
Tera Contributor

A few posts ago I mentioned that you can use the hasOwnProperty() method to distinguish between a property that's actually undefined and one that exists but has a value of undefined.

Ok, my young friend says. But surely there's an easier, more elegant way to do this — that would be the "in thing" if it existed, just like my hat!

Why, yes it would, my dear...

Here's some code that sets up the issue:


var xerces = {a:45, b:12, c:undefined, d:null};
gs.log(xerces.c);
gs.log(xerces.e);

When we run that code, both log outputs will show "undefined", even though one of the properties (c) actually exists. In the previous post I noted that you could do something like this:

var xerces = {a:45, b:12, c:undefined, d:null};
gs.log(xerces.c + ', but exists: ' + xerces.hasOwnProperty('c'));
gs.log(xerces.e + ', but exists: ' + xerces.hasOwnProperty('e'));

This is the awkward, ugly syntax my young friend is complaining about. Here's a different way:

var xerces = {a:45, b:12, c:undefined, d:null};
gs.log(xerces.c + ', but exists: ' + ('c' in xerces));
gs.log(xerces.e + ', but exists: ' + ('e' in xerces));

It's the "in" thing! Well, the "in" operator, actually.

But it gets better. The in property is also useful for check for properties that aren't enumerable. Consider this code:

var harry = [4,87,23,982,2];
for (var name in harry)
gs.log(name);

If you run this code, you'll see that it enumerates properties named "0" through "4" — the elements of the of the array. But you know that the array has other properties, such as its methods. For example, the Array class has a join() method. This method (like many built-in methods and properties) is not enumerable, so it never gets picked up by the for () loop. But the in operator can see it quite nicely (while the hasOwnProperty() method does not):

var harry = [4,87,23,982,2];
gs.log(harry.join(' - '));
gs.log(harry.hasOwnProperty('join'));
gs.log('join' in harry);

Run that code, and you'll see this:

4 - 87 - 23 - 982 - 2
false
true

The first line proves that the hasOwnProperty() method is actually there (and it works!). The second line shows that the hasOwnProperty() method does not detect it. Finally, the last line shows that the in thing picked it up just fine...