Access Array with For-of

Course- Javascript >

JavaScript has various methods for handling arrays, as you read about in section,“Javascript Arrays.” Apart from while and for loops, you can also use for-in. Unfortunately, this loop visits all of an array’s named properties, not just the actual array values:

"use strict";
let arr1 = [ 6, 5, 7, 9 ];
arr1.greeting = "hi";
for (var x in arr1) {
console.log(x); // logs "0", "1", "2", "3", "greeting"
}                     
                     

To get around this problem, ECMAScript 6 introduces the for-of construct, which iterates over just the property values:

for (var y of arr1) {
console.log(y); // logs "6", "5", "7", "9"
}                     
                     

Note the use of the directive "use strict" in the preceding code snippet. This directive, introduced in ECMAScript 5, indicates that JavaScript should execute in strict mode, a more rigid set of interpreter rules, and is currently necessary to use certain ECMAScript 6 features.

JAVASCRIPT TRANSPILATION

The examples presented so far in this section are fine for testing ECMAScript 6 features, but at the time of writing they are not ready for use in your production code. Few visitors to your website will be using a browser with strong ECMAScript 6 support. You can start preparing for the future, though.

Traceur is a Google project intended to take ECMAScript 6 code and process it into ECMAScript 5 code that is compatible with most browsers using their default settings. It doesn’t support all of the ECMAScript 6 features, but new features are being added all the time.

You can read about the project at https://code.google.com/p/traceurcompiler/wiki/GettingStarted, and also download the code to try for yourself at https://github.com/google/traceur-compiler.