Hacker Timesnew | past | comments | ask | show | jobs | submitlogin

I don't know why the second-top one has so many votes, it's completely wrong.

   var x = 1;
   var y = 3;
   var list = [0,1,2];
   x in list; //true
   y in list; //false
   1 in list; //true
   y in [3,4,5]; //true
That last expression is false. This is because the "in" operator does not check for values in the list; it checks for keys. Try this:

   javascript:alert(3 in [3,4,5])
The only things that will be true for "X in [3,4,5]" are 0, 1, and 2 for X (since these are the natural keys for the terms in the array). More specifically, "in" in general checks for members associated with objects (e.g., keys in an array, methods of a class, etc.):

   javascript:alert("The setFlag method " + ("setFlag" in {setFlag:function(){}} ? "exists" : "does not exist"))
EDIT: This makes the keyword considerably less useful (since indexOf doesn't work for the Array object in IE--although jQuery has a way around this), although it can be used to replace the less elegant

   if (typeof object.method == "undefined")


Oh whoa! I never realized I could just type "javascript:..." into the status bar in Firefox and have it run it. That's awesome. (In retrospect, I realize I should've realized it, because I've always known that the javascript links are "javascript:functionCall()" or some such.)


Other fun 'in' trivia: It looks through the object's entire prototype chain: http://yuiblog.com/blog/2006/09/26/for-in-intrigue/


Go post a comment on that answer to clarify it.




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: