for own(...) loop (spin-off from Re:, hasOwnProperty(), and inheritance)

Andy Earnshaw andy at
Wed Nov 9 15:38:25 PST 2011

Should provide sugar for the recommended pattern? To make it compose
with declarations and destructuring in the for head, it should use a
contextual keyword immediately after 'for':


  for own (i in o) {




This is a small thing but it might pay off in the long run.


I was thinking of raising a similar suggestion, but I wasn't sure when to
jump in and bring it up.  However, I think it could be more useful to
introduce another operator like `in` as syntactic sugar for `hasOwnProperty`
and have it work in a `for` loop similar to how `` works too.


  /* Desugared property check -> */ o.hasOwnProperty(prop)

  /* Sweetened property check -> */ prop on o


  /* Desugared loop -> */ for (i in o) { if o.hasOwnProperty(i) { ... }

  /* Sweetened loop -> */ for (i on o) { ... }


I could see it being useful as an operator in situations where you might
have an object map:


  var obj = { key1: val1, key2: val2 }


  if ("key1" on obj) {                  

     // ...



I think Dr Rauschmayer mentioned Python's `on` and I think it fits in here
quite nicely.  `in` for anywhere in the chain, `on` for direct properties.
If it's a little too close for comfort, you could stick with `own` or
reverse the operands and call it `hasown`.  Perhaps that would seem too
inconsistent, though.  Overall, I think it's a great idea.  It's fairly
common for developers to forget to do a `hasOwnProperty` check when
enumerating.  As for `Object.keys(o).forEach()`, the speed just doesn't
compare and it doesn't look too great.


Andy Earnshaw

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the es-discuss mailing list