Iteration

Bashar Ayyash
2 min readAug 29, 2015

--

This post is a part of Starter to ES6

ES6 introduces iterator as feature of the language by combining the new iteration methods with Array and new collection types (Set(), map()), iterator objects include next() method which returns a result object, the result object has two properties value and done, value property is the next value and done property is a boolean value returns true if the current element is the last element and no other values after.

Implement next() method in ES5:

function createNewIterator(items) { if (items === void 0) { items = []; }
var i = 0;
return {
next: function () {
var done = (i >= items.length);
var value = !done ? items[i++] : undefined;
return { done: done, value: value };
}
};
}

var iterator = createNewIterator([1, 2, 3]);
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());

In EC6 iterators presented in different areas, understanding the ways to use iterators make dealing with collection easier in ES6. I will show you below how to use the different iterators methods:

  • In for-of loop, which is ES6 new loop, internally it calls the next() method, the iterability is required by the iterable item or the loop will not work. for-of loops over (Set(), Map(), Array) or any other iterable object

example of for-of loop

for (let x of [‘a’, ‘b’, ‘c’]) {

console.log(x);

}

Another example shows index and value of an array

let arr = [‘a’, ‘b’, ‘c’];

for (let pair of arr.entries()) {

console.log(pair);

}

Example of ES6 Array method from(), method used to convert objects with length property and indexed items.

let arrObject = { length: 3, 0: ‘a’, 1: ‘b’, 2: ‘c’ };

for (let x of arrObject) { // TypeError
console.log(x);
}

for (let x of Array.from(arrObject)) { // OK
console.log(x);
}

You can iterate over object entries by using ES6 generator (Explained after)

function* objEntries(obj) {

for (let key of Object.keys(obj)) {
yield [key, obj[key]];
}
}

let arr = { first: ‘Bashar’, last: ‘Ayyash’};
for(let [key, val] of objEntries(arr)){
console.log(`Key: ${key}, Value: ${val}`);
}

This post is a part of Starter to ES6

--

--

Bashar Ayyash

Front End Developer, I’m confident that Vue.js is as powerful as React, but way more flexible and a lot easier to learn