Issues with “in” operator in JavaScript – using hasOwnProperty() function

Imagine you are using an JavaScript array on the client-side that stores some client-side components (or vanilla HTML elements) by their IDs – for what ever reason. Now imagine you have a function that checks if a given ID is in that particular array. Based on the result, some (different) logic is triggered. Pretty common scenario – nothing fancy.

Code could look like this:

var componentIds = new Array();
componentIds["table"] = "my table component";
componentIds["tree"] = "my tree component";

containsComponent = function(compId)
  if((compId in componentIds))
    return true;
    return false;

//some callings callings...
alert("tree: in array ? -> " + containsComponent("tree"));
alert("myTabe: in array ? -> " + containsComponent("myTree"));
alert("table: in array ? -> " + containsComponent("table"));

Now I noticed some problem when your component ID is a “reserved” word. Like “map” or “push”. Does that ring your ear ? Yes, correct – that’s the name of a JavaScript function of the Array class:

// huh ???
alert("map: in array ? -> " + containsComponent("map"));

So that means on an empty array a check for “map” (or “slice”) would return TRUE. That can cause some interesting troubles and side effects, well BUGs 🙂

The problem with “in” operator is that it does not only check if the damn array does have a key with the “name” in question – it also checks for functions on the prototype. I talked to my colleague Blake Sullivan about avoiding to query for the function. He simply suggested to just use the “hasOwnProperty()” function instead of checking if the returned value is type of “function”. I personally never used that function before (and never seen it in code before) – but it helps to avoid odd and nasty issue 😉



Posted in ajax, javascript, web²
3 comments on “Issues with “in” operator in JavaScript – using hasOwnProperty() function
  1. Why are you using an array in the first place? Use an object:

    var components = {}

    Now, unless your code or some libraray extends Object.prototype, components won’t have any existing properties.

  2. Odi says:

    Try also:
    var a = new Array();

    This is really wrong. I would say it’s a bug in Firefox. IE doesn’t do that.

  3. Odi, no it isn’t. You’re misusing Arrays.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

August 2009
« Jul   Dec »
%d bloggers like this: