Idiomatic for ... in

  • Follow


Hey folks,

One thing I've been wondering about lately is how to write a for (key in object) loop in a nice, idiomatic manner.

What to me seems the obvious shape for it is

for (key in object) {
  if (object.hasOwnProperty(key)) {
    doStuff();
  }
}

but that is a wee bit too verbose, and eats up an indent level unnecessarily. I've also seen the form

for (key in object) {
  if (!object.hasOwnProperty(key)) {
    continue;
  }
  doStuff();
}

which doesn't eat up the extra indent level, but is longer, and suffers from not making it quite as obvious that the if is filtering the keys. I've personally come to favour

for (key in object) if (object.hasOwnProperty(key)) {
    doStuff();
}

Which, to my eyes, is nice and compact, but I really haven't seen it anywhere else, so fails a bit on the
surprise factor for anyone else reading my code.

So, what do you guys like, and why?
0
Reply Pedro 3/28/2011 3:44:08 PM

Pedro Pinheiro schrieb:

> for (key in object) {
>   if (object.hasOwnProperty(key)) {
>     doStuff();
>   }
> }

Why not wrap this in a function? (Untested:)

function iterate( object, callback )
{
     for ( key in object ) {
         if ( object.hasOwnProperty( key ) ) {
             callback( object, key );
         }
     }
}

// Usage
iterate( someObject, doStuff );

Greetings,
Thomas

-- 
Ce n'est pas parce qu'ils sont nombreux � avoir tort qu'ils ont raison!
(Coluche)
0
Reply Thomas 3/28/2011 4:27:45 PM


On 28/03/2011 12:44, Pedro Pinheiro wrote:
> Hey folks,
>
> One thing I've been wondering about lately is how to write a
 > for (key in object) loop in a nice, idiomatic manner.
>
> What to me seems the obvious shape for it is
>
> for (key in object) {
>    if (object.hasOwnProperty(key)) {
>      doStuff();
>    }
> }


<http://javascript.crockford.com/code.html>

> but that is a wee bit too verbose, and eats up an indent
 > level unnecessarily. I've also seen the form
>
> for (key in object) {
>    if (!object.hasOwnProperty(key)) {
>      continue;
>    }
>    doStuff();
> }
>
> which doesn't eat up the extra indent level, but is longer,
 > and suffers from not making it quite as obvious that the if
 > is filtering the keys. I've personally come to favour
>
> for (key in object) if (object.hasOwnProperty(key)) {
>      doStuff();
> }
>
> Which, to my eyes, is nice and compact, but I really haven't seen it anywhere else, so fails a bit on the
> surprise factor for anyone else reading my code.
>
> So, what do you guys like, and why?


I'd suggest that you stick to the code conventions:
<http://javascript.crockford.com/code.html>

The following code snippet should be the preferred form in JavaScript:

   for (variable in object) {
     if (object.hasOwnProperty(variable)) {
       // statements
     }
   }

-- 
Joao Rodrigues (J.R.)
0
Reply groups_jr-1 (102) 3/28/2011 10:20:00 PM

J.R. wrote:

> Pedro Pinheiro wrote:
>> One thing I've been wondering about lately is how to write a
>> for (key in object) loop in a nice, idiomatic manner.
>>
>> What to me seems the obvious shape for it is
>>
>> for (key in object) {
>>    if (object.hasOwnProperty(key)) {
>>      doStuff();
>>    }
>> }
> 
> <http://javascript.crockford.com/code.html>

The code above complies with the conventions set forth in this document.

>> […]
>> So, what do you guys like, and why?
> 
> I'd suggest that you stick to the code conventions:
> <http://javascript.crockford.com/code.html>
> 
> The following code snippet should be the preferred form in JavaScript:
> 
>    for (variable in object) {
>      if (object.hasOwnProperty(variable)) {
>        // statements
>      }
>    }
> 

I do suggest that you start thinking independently.  Syntactically, the name 
of the value which holds the current property name in for-in iteration may 
be anything that can be produced by /LeftHandSideExpression/.  In a strict 
semantic sense, obviously neither of the terms "key" nor "variable" is 
correct for it; only "property name" is.  In a more loose semantic sense, a 
property name can certainly be considered a key (of a hash table) by which a 
certain property value is accessed.

IOW, there was nothing wrong with this code in the first place.  Besides,
despite his contributions on the topic it is certainly not Douglas Crockford 
who sets the standards against which ECMAScript-based code should be 
measured; see for example (the complaints about) jslint.  It is incorrect to 
present his ideas of code conventions as "/the/ code conventions".  Contrary 
to that of Java, there are no official code conventions for the JavaScript 
language or all ECMAScript implementations.  Instead, there are some best 
practices which several developers agree on.


PointedEars
-- 
Use any version of Microsoft Frontpage to create your site.
(This won't prevent people from viewing your source, but no one
will want to steal it.)
  -- from <http://www.vortex-webdesign.com/help/hidesource.htm> (404-comp.)
0
Reply PointedEars (2025) 3/28/2011 10:56:33 PM

On Mar 29, 1:44 am, Pedro Pinheiro <pdpinhe...@gmail.com> wrote:
> Hey folks,
>
> One thing I've been wondering about lately is how to write a for (key in object) loop in a nice, idiomatic manner.
>
> What to me seems the obvious shape for it is
>
> for (key in object) {
>   if (object.hasOwnProperty(key)) {
>     doStuff();
>   }
>
> }
>
> but that is a wee bit too verbose, and eats up an indent
> level unnecessarily. I've also seen the form

That is the only way to do it safely in general, though if you want
less code:

for (var p in o) {
  o.hasOwnProperty(p) && doStuff();
}

may suit - but if the only reason to do it is to save a few characters
I'm not convinced it's a good idea. It might keep Crockford happy
though. :-)

ES5 introduces Object.keys[1] that returns an array of an object's
enumerable, own property names, but it doesn't save any typing:

// Substitute if Object.keys isn't a function
if (Object.keys != 'function') {
  Object.keys = function(o) {
    var a = [];
    for (var p in o) {
      if (o.hasOwnProperty(p)) {
        a.push(p);
      }
    }
    return a;
  }
}

// Use Object.keys
if (typeof Object.keys == 'function') {
  var keys = Object.keys(o);
  for (var i=0, iLen=keys.length; i<iLen; i++) {
    // do stuff with keys
  }
}

Note that there is also Object.getOwnPropertyNames, but it returns
both enumerable and non-enumerable own properties.

1. Object.keys also has:

  "If an implementation defines a specific order of enumeration for
   the for-in statement, that same enumeration order must be
   used in step 5 of this algorithm."


--
Rob
0
Reply rgqld (176) 3/29/2011 1:26:41 AM

On Mon, 28 Mar 2011 at 08:44:08, in comp.lang.javascript, Pedro Pinheiro
wrote:

  <snip>
>for (key in object) if (object.hasOwnProperty(key)) {
>    doStuff();
>}
 ^
  <snip>

That close bracket looks as though it was opened a long way off the top
of the screen. Saving a couple of space chars isn't worth it.

Why not have the courage to prove you understand the syntax :

  for (key in object)
    if (object.hasOwnProperty(key))
      doStuff();

or even

  for (key in object) if (object.hasOwnProperty(key)) doStuff();


  John
-- 
John Harris
0
Reply john2010 (326) 3/29/2011 9:54:31 AM

John G Harris wrote:

> Pedro Pinheiro wrote:
>> for (key in object) if (object.hasOwnProperty(key)) {
>>     doStuff();
>> }
>  ^
>   <snip>
> 
> That close bracket looks as though it was opened a long way off the top
> of the screen. Saving a couple of space chars isn't worth it.

ACK
 
> Why not have the courage to prove you understand the syntax :
> 
>   for (key in object)
>     if (object.hasOwnProperty(key))
>       doStuff();

Because this isn't Python.
 
> or even
> 
>   for (key in object) if (object.hasOwnProperty(key)) doStuff();

Because that's a debugging and refactoring nightmare.


PointedEars
-- 
Anyone who slaps a 'this page is best viewed with Browser X' label on
a Web page appears to be yearning for the bad old days, before the Web,
when you had very little chance of reading a document written on another
computer, another word processor, or another network. -- Tim Berners-Lee
0
Reply PointedEars (2025) 3/29/2011 11:40:53 AM

On Mar 28, 7:44=A0pm, Pedro Pinheiro <pdpinhe...@gmail.com> wrote:
> for (key in object) if (object.hasOwnProperty(key)) {
> =A0 =A0 doStuff();
>
> }
>
> Which, to my eyes, is nice and compact, but I really haven't seen it anyw=
here else, so fails a bit on the
> surprise factor for anyone else reading my code.

The code is valid and from the human language semantic point of view
looks pleasurable. Yet I personally object skipping block brackets
even if allowed. Even more disturbing here that the same line
demonstrate two different choices for block brackets: omitted for for-
in and used for if-else. I would prefer the coding consistency over
any belletristic achievements. If it is possible to write a working
program in say Perl as a piece of a poetry, it doesn't mean that we
have to :-)

So my personal opinion: definitely fine for personal projects, should
be avoided for an open code project with many participant. In the
latter case: i) consistency, ii) strict syntax rules (no skipped
brackets or ;'s), iii) detailed comments. With this in place (iii) can
be as idiomatic or belletristic as particular participant feels to.
IMHO.
0
Reply schools_ring (206) 3/29/2011 11:42:59 AM

In article <imr1ik$vou$4@speranza.aioe.org>,
 "J.R." <groups_jr-1@yahoo.com.br> wrote:

> On 28/03/2011 12:44, Pedro Pinheiro wrote:
> > Hey folks,
> >
> > One thing I've been wondering about lately is how to write a
>  > for (key in object) loop in a nice, idiomatic manner.
> >
> > What to me seems the obvious shape for it is
> >
> > for (key in object) {
> >    if (object.hasOwnProperty(key)) {
> >      doStuff();
> >    }
> > }
> 
> <http://javascript.crockford.com/code.html>
> 
> > but that is a wee bit too verbose, and eats up an indent
>  > level unnecessarily. I've also seen the form
> >
> > for (key in object) {
> >    if (!object.hasOwnProperty(key)) {
> >      continue;
> >    }
> >    doStuff();
> > }
> >
> > which doesn't eat up the extra indent level, but is longer,
>  > and suffers from not making it quite as obvious that the if
>  > is filtering the keys. I've personally come to favour
> >
> > for (key in object) if (object.hasOwnProperty(key)) {
> >      doStuff();
> > }
> >
> > Which, to my eyes, is nice and compact, but I really haven't seen it 
> > anywhere else, so fails a bit on the
> > surprise factor for anyone else reading my code.
> >
> > So, what do you guys like, and why?

> I'd suggest that you stick to the code conventions:
> <http://javascript.crockford.com/code.html>
> 
> The following code snippet should be the preferred form in JavaScript:
> 
>    for (variable in object) {
>      if (object.hasOwnProperty(variable)) {
>        // statements
>      }
>    }

And so all your "// statements" are indented one more level than is 
necessary. I subscribe to the view that says get rid of the 
uninteresting cases as soon as possible, and then concentrate on the 
rest (so I'm bored with any argument in favour of SESE). In this case, 
that becomes:

     for  (variable in object)
          {
          if  (object.hasOwnProperty(variable)==false)  continue;
          // statements
          }

Only one pair of braces needed, and because they are aligned, I can find 
the matching pair easily.

-- 
Tim

"That excessive bail ought not to be required, nor excessive fines imposed,
nor cruel and unusual punishments inflicted"  --  Bill of Rights 1689
0
Reply timstreater (943) 3/29/2011 3:14:22 PM

On 29/03/2011 12:14, Tim Streater wrote:
>> "J.R." wrote:
>>
>> The following code snippet should be the preferred form in JavaScript:
>>
>> for (variable in object) {
>>   if (object.hasOwnProperty(variable)) {
>>     // statements
>>   }
>> }
>
> And so all your "// statements" are indented one more level than is
> necessary. I subscribe to the view that says get rid of the
> uninteresting cases as soon as possible, and then concentrate on the
> rest (so I'm bored with any argument in favour of SESE). In this case,
> that becomes:
>
> for (variable in object)
> {
> if (object.hasOwnProperty(variable)==false) continue;
> // statements
> }
>
> Only one pair of braces needed, and because they are aligned, I can find
> the matching pair easily.
>

Okay, there's no accounting for taste. However, there are some code 
editors, such as Notepad++ and Aptana Studio, which help me a lot in 
terms of finding the matching pair of curly brackets, particularly with 
many code lines.

-- 
Joao Rodrigues (J.R.)
0
Reply groups_jr-1 (102) 3/29/2011 5:45:10 PM

In article <imt5r7$mmp$1@speranza.aioe.org>,
 "J.R." <groups_jr-1@yahoo.com.br> wrote:

> On 29/03/2011 12:14, Tim Streater wrote:
> >> "J.R." wrote:
> >>
> >> The following code snippet should be the preferred form in JavaScript:
> >>
> >> for (variable in object) {
> >>   if (object.hasOwnProperty(variable)) {
> >>     // statements
> >>   }
> >> }
> >
> > And so all your "// statements" are indented one more level than is
> > necessary. I subscribe to the view that says get rid of the
> > uninteresting cases as soon as possible, and then concentrate on the
> > rest (so I'm bored with any argument in favour of SESE). In this case,
> > that becomes:
> >
> > for (variable in object)
> > {
> > if (object.hasOwnProperty(variable)==false) continue;
> > // statements
> > }
> >
> > Only one pair of braces needed, and because they are aligned, I can find
> > the matching pair easily.
> >
> 
> Okay, there's no accounting for taste. However, there are some code 
> editors, such as Notepad++ and Aptana Studio, which help me a lot in 
> terms of finding the matching pair of curly brackets, particularly with 
> many code lines.

Sure and TextWrangler has a similar feature. But I don't use it often 
because I don't need to.

-- 
Tim

"That excessive bail ought not to be required, nor excessive fines imposed,
nor cruel and unusual punishments inflicted"  --  Bill of Rights 1689
0
Reply timstreater (943) 3/29/2011 6:55:02 PM

On Tue, 29 Mar 2011 at 13:40:53, in comp.lang.javascript, Thomas
'PointedEars' Lahn wrote:
>John G Harris wrote:

  <snip>
>> Why not have the courage to prove you understand the syntax :
>>
>>   for (key in object)
>>     if (object.hasOwnProperty(key))
>>       doStuff();
>
>Because this isn't Python.

No, it's more like C, C++, Java, and C#, but it's where Python got its
peculiar ideas from.


>> or even
>>
>>   for (key in object) if (object.hasOwnProperty(key)) doStuff();
>
>Because that's a debugging and refactoring nightmare.

Tell that to John Stockton  :-)

  John
-- 
John Harris
0
Reply john2010 (326) 3/30/2011 10:23:29 AM

John G Harris wrote:

> Thomas 'PointedEars' Lahn wrote:
>> John G Harris wrote:
>>> Why not have the courage to prove you understand the syntax :
>>>
>>>   for (key in object)
>>>     if (object.hasOwnProperty(key))
>>>       doStuff();
>> Because this isn't Python.
> 
> No, it's more like C, C++, Java, and C#, but it's where Python got its
> peculiar ideas from.

I do not know about C(\+\+|#)? code conventions, but the official Java Code 
Conventions require braces there.  And that is good so.

<http://www.oracle.com/technetwork/java/codeconventions-142311.html#449>

>>> or even
>>>
>>>   for (key in object) if (object.hasOwnProperty(key)) doStuff();
>>
>> Because that's a debugging and refactoring nightmare.
> 
> Tell that to John Stockton  :-)

No, I won't.  Code-style-wise at least, he cannot be reasoned with.


PointedEars
-- 
var bugRiddenCrashPronePieceOfJunk = (
    navigator.userAgent.indexOf('MSIE 5') != -1
    && navigator.userAgent.indexOf('Mac') != -1
)  // Plone, register_function.js:16
0
Reply PointedEars (2025) 3/30/2011 4:34:14 PM

Tim Streater wrote:

> Thomas 'PointedEars' Lahn wrote:
>> John G Harris wrote:
>> > Thomas 'PointedEars' Lahn wrote:
>> >> John G Harris wrote:
>> >>> Why not have the courage to prove you understand the syntax :
>> >>>
>> >>>   for (key in object)
>> >>>     if (object.hasOwnProperty(key))
>> >>>       doStuff();
>> >> Because this isn't Python.
>> > 
>> > No, it's more like C, C++, Java, and C#, but it's where Python got its
>> > peculiar ideas from.
>> 
>> I do not know about C(\+\+|#)? code conventions, but the official Java
>> Code Conventions require braces there.  And that is good so.
>> 
>> <http://www.oracle.com/technetwork/java/codeconventions-142311.html#449>
> 
> For "if" and "for", at least (I didn't look any further), these have to
> be the shittiest layout conventions I've ever seen.

Oracle screwed up the formatting when taking over Sun; compare with the 
original here: 

<http://replay.waybackmachine.org/20090228064950/http://java.sun.com/docs/codeconv/html/CodeConventions.doc6.html#449>


PointedEars
-- 
var bugRiddenCrashPronePieceOfJunk = (
    navigator.userAgent.indexOf('MSIE 5') != -1
    && navigator.userAgent.indexOf('Mac') != -1
)  // Plone, register_function.js:16
0
Reply PointedEars (2025) 3/30/2011 6:28:23 PM

In article <7357600.eNJFYEL58v@PointedEars.de>,
 Thomas 'PointedEars' Lahn <PointedEars@web.de> wrote:

> John G Harris wrote:
> 
> > Thomas 'PointedEars' Lahn wrote:
> >> John G Harris wrote:
> >>> Why not have the courage to prove you understand the syntax :
> >>>
> >>>   for (key in object)
> >>>     if (object.hasOwnProperty(key))
> >>>       doStuff();
> >> Because this isn't Python.
> > 
> > No, it's more like C, C++, Java, and C#, but it's where Python got its
> > peculiar ideas from.
> 
> I do not know about C(\+\+|#)? code conventions, but the official Java Code 
> Conventions require braces there.  And that is good so.
> 
> <http://www.oracle.com/technetwork/java/codeconventions-142311.html#449>

For "if" and "for", at least (I didn't look any further), these have to 
be the shittiest layout conventions I've ever seen.

-- 
Tim

"That excessive bail ought not to be required, nor excessive fines imposed,
nor cruel and unusual punishments inflicted"  --  Bill of Rights 1689
0
Reply timstreater (943) 3/30/2011 6:33:18 PM

In article <5614433.4DdEvYhyI6@PointedEars.de>,
 Thomas 'PointedEars' Lahn <PointedEars@web.de> wrote:

> Tim Streater wrote:
> 
> > Thomas 'PointedEars' Lahn wrote:

[snip]

> >> I do not know about C(\+\+|#)? code conventions, but the official Java
> >> Code Conventions require braces there.  And that is good so.
> >> 
> >> <http://www.oracle.com/technetwork/java/codeconventions-142311.html#449>
> > 
> > For "if" and "for", at least (I didn't look any further), these have to
> > be the shittiest layout conventions I've ever seen.
> 
> Oracle screwed up the formatting when taking over Sun; compare with the 
> original here: 
> 
> <http://replay.waybackmachine.org/20090228064950/http://java.sun.com/docs/code
> conv/html/CodeConventions.doc6.html#449>

Thanks for the link.

Fortunately I don't have to bother with conventions I don't like.

-- 
Tim

"That excessive bail ought not to be required, nor excessive fines imposed,
nor cruel and unusual punishments inflicted"  --  Bill of Rights 1689
0
Reply timstreater (943) 3/30/2011 7:35:14 PM

15 Replies
247 Views

(page loaded in 0.216 seconds)

Similiar Articles:













7/23/2012 2:59:25 PM


Reply: