One of the things you do most often as a game designer is loop through arrays. Does the following code look familiar?
let planets = ["jupiter", "venus", "saturn", "mars"];
for (let i = 0; i < planets.length; i++) {
planet = planets[i];
console.log(planet);
}
It displays the name of each planet in the console:
jupiter
venus
saturn
mars
This is a classic bit of code, which gets a nice update with ES6. Because the i
loop index counter is defined using let
, it is local to the for
loop. That means you can reuse the variable name i in as many other loops as you like, and their values won’t conflict.
Our dear old for loop still has its place in JavaScript, and often it’s still the best tool for the job. But with JavaScript ES6 (and ES5) you have some convenient new methods for looping through arrays that can help make your code a lot more readable.
Note
for
loops tend to be highly optimized by JavaScript engines like V8 and SpiderMonkey, and so they are still the safest bet for games where you may be looping through thousands of objects each frame. In this book I’ll highlight when it’s generally safe to use one of the newer loop methods, and when you should probably play it safe with afor
loop. If you’re curious about the relative performance differences between different loop methods on the platform you’re using, visit jsperf.com and run a few test cases.