Skip to content

Instantly share code, notes, and snippets.

@jhs
Created August 10, 2012 16:34
Show Gist options
  • Save jhs/3315407 to your computer and use it in GitHub Desktop.
Save jhs/3315407 to your computer and use it in GitHub Desktop.
Looping syntax
for (var thing in {'foo':1, 'bar':1, 'neat':1}) {
console.log('doing ' + thing)
doing(thing)
}
@jhs
Copy link
Author

jhs commented Aug 10, 2012

I will begin trying this style out. See how it fits.

It is tight syntax to iterate through a "list" of strings (in an undefined order). It is not the ideal for-in syntax; but it's valid syntax, and iterating through a hard-coded set of strings is really common.

@isaacs
Copy link

isaacs commented Aug 10, 2012

Why is this better than a forEach on an array literal?

;['foo','bar','neat'].forEach(function (thing) {
  console.log('doing ' + thing)
  doing(thing)
})

@jhs
Copy link
Author

jhs commented Jan 1, 2013

I am kind of anti the leading semicolon. Of course I understand its syntactic need. But I kind of feel like, if it's worth iterating through a set of strings, it's worth giving that set a name.

var keywords = ['foo', 'bar', 'neat']
keywords.forEach(/* ... */)

I realize that my point undermines the entire purpose of this Gist. And in the intervening five months I had not even thought to try the new syntax. So it never caught on, even in its author's mind.

P.S. Happy new year!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment