JavaScript for game designer: Getting Loopy with Arrays

Anton Merinov

Anton Merinov

The author of the article. Interests, skills: Professional administration of Oracle Database, web development, IT-World. More details.

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];

It displays the name of each planet in the console:


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 a for loop. If you’re curious about the relative performance differences between different loop methods on the platform you’re using, visit and run a few test cases.

Вас заинтересует / Intresting for you:

Why is JavaScript a Good Choic...
Why is JavaScript a Good Choic... 1107 views Денис Thu, 20 Sep 2018, 15:50:46
JavaScript for game designer: ...
JavaScript for game designer: ... 737 views Antoni Tue, 27 Nov 2018, 14:28:10
Working with a database in Wor...
Working with a database in Wor... 99 views Андрей Васенин Tue, 16 Nov 2021, 16:23:40
What is RESTful? Full descript...
What is RESTful? Full descript... 1037 views Zero Cool Wed, 31 Oct 2018, 09:40:56
Log in to comment