ECMAScript6 – for … of loop

ECMAScript6 supports a new for...of loop, and there are couple reasons to have this new loop in next version of ECMAScript.

You can start testing those for...of loop on FireFox because it has better support for ECMAScript6.

From harmony:iterators, it has very clear explanation about why they came out this proposal. I  just put my summary in here:

  1. Property is NOT the only data set we want to iterate over
  2. When iterating an array, it produces array index, not array value
  3. for...in loop will visit prototype
  4. for...in loop is not conveniently customizable

Here is how for...of loop using over Array, Set, and Map data types. You can see the original example from harmony:iterators.

for (var val of ['AA', 'BB', 'CC']) {
    console.log(val); // 'AA', 'BB', 'CC'
}

var s = Set([1, 3, 4, 2, 3, 2, 17, 17, 1, 17]);
for (var val of s) {
    console.log(val); // 1, 3, 4, 2, 17
}

var m = new Map;
m.set('Castiel', 'Angel');
m.set('Dean', 'Human');
for (var [name, value] of m) {
    console.log(name + ' = ' + value); // 'Castiel = Angel', 'Dean = Human'
}

Related Articles:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s