Skip to content

Instantly share code, notes, and snippets.

@juliocesar
Created May 3, 2013 04:42
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save juliocesar/5507247 to your computer and use it in GitHub Desktop.
Save juliocesar/5507247 to your computer and use it in GitHub Desktop.
ES6 - for loops
// ES6 for loops
// =============
// Things in ES6 can be "iterable". Arrays are iterable by default.
var fruits = ['Apple', 'Banana', 'Grape'];
for (var fruit of fruits)
console.log('Fruit: ' + fruit);
// => "Fruit: Apple"
// => "Fruit: Banana"
// => "Fruit: Grape"
// Objects apparently not iterable as anyone in the planet would expect.
// You need to declare an iterator which is a method that defines how
// each property is return.
// Y U NO USE A DEFAULT ITERATOR?!
var person = { name: 'Joe', age: 25, bio: 'Long bio here' };
var attributes = function(person) {
for (var attr in person) yield [attr, person[attr] ]
};
for (var [attribute, value] of attributes(person))
console.log(attribute + ': ' + value);
@Zorgatone
Copy link

You should avoid unguarded for/in loops on objects. You have to check for object.hasOwnProperty()

@Zorgatone
Copy link

I believe you also forgot the asterisk in the attributes generator function

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