How to convert a string to a boolean (the right way)

There are a couple of ways to convert a string variable to a boolean variable in Javascript. However, when doing this, you have to be kind of careful: it’s kind of easy to mess up this sort of logic and doing it wrong can result in some nasty bugs. So, in order to save you a headache or two, I’ve detailed how to do it properly in this article. Read on, if you’re interested.

1) You might be tempted to say if(myString)…

…and this would appear to work, for a while. However, it’s really the wrong way to go about this. Observe:

var myString = true;
if (myString) {
    // this should evaluate to true because myString = "true", and it does. Good!
if (!myString) {
    // uh oh! This evaluates to true as well. Why? Because if(!myString)
    // is checking to see if myString *exists*, not if it's *true*.

As I mentioned, if(!myString) evaluates to true because that statement only checks if myString exists (e.g. if it’s not undefined or null), not if it evaluates to false.

2) What about creating a boolean object from the string?

Why not try to create a Boolean object from the string? Well, you’d run into an issue similar to the previous problem. Let’s let some example code do the talking, though, have a look:

var myString = "true";
if(Boolean(myString)) {
    // very good, this if statement evaluates to true correctly!
if(!Boolean(myString)) {
    // and this one evaluates to false! Our problems are solved!
var myOtherString = "false";
if(Boolean(myOtherString)) {
    // ...or are they? This evaluates to true, although we clearly set it to "false"!

As you can see, if(Boolean(“false”)) evaluates to true–why? When you create a new Boolean object from a string, it doesn’t try to check whether the string equals “true” or “false”. Instead, rather misleadingly, it checks whether the variable is a non-falsy value (e.g. a value that evalutes to false–0, undefined, an empty string, null, etc). Because myString is not an empty string, the Boolean evaluates to true–even if myString equals false.

3) Right, let’s try comparing our string against the string “true”

Really, the correct way we should be going about this is to check if our string equals “true” — if so, then our string is obviously “true”. Otherwise, it must be false. We can do it this way:

var myString = "true";
if(myString == "true") {
    // this evaluates to true correctly, myString is true
if(myString == "false") {
    // this evaluates to false, also correct, since myString doesn't equal false.

Wonderful, it looks like our problem is solved! But, you know something? The above code is kind of messy and a bit long just to check if our string is “true” or not. Let’s see if we can’t clean it up a bit:

myString = (myString == "true");

Ahh, nice and clean. Just the way I like it! (note: the parentheses are just there for clarity–if you don’t like them or you’re extra extra concerned about line length, removing them won’t cause any errors).

For loops, while loops, fruit loops…

There are a lot of different kinds of ways to write loops in Javascript. You have your standard for loop and while loop, but beyond that you have the do-while loop, the object properties loop, and lots of different variation of all four “basic” loops. In this post, we’ll examine the four basic loops, the reverse for loop, the reverse while loop, the short reverse while loop, object property loops, and more. I’ll also explain a bit about loop unrolling and where/how it can help you optimize your code. Read on, if you dare!

The classic for loop

What I like to call the classic for loop is perhaps the most basic of all loops in Javascript. It looks like this:

for(var i = 0; i<10; i++) { 
    // do stuff with i 

This is the basic loop model provided by Javascript and is by far the most common variation of the for loop. You initialize an iterator (i), set a finish condition for i, and finally specify how i will be modified each iteration of the loop. Since i++ is just a statement, it’s possible to modify i however you want in the loop header using statement operators. for(var i = 0; i<10; i+= 2) will increment i by two each iteration, for example.

Note: You have to be careful. If you initialize the loop without putting var in front of the iterator variable (like this: for(i = 0; i<10; i++)), you’ll turn it into a global variable, which may not be what you were intending to do.

Using the for loop to iterate through an array

Assuming you have an array called things, you can use a for loop to iterate through it like so:

 for(var i = 0, len = things.length; i<len; i++) { 
     var currentThing = things[i]; 

The classic while loop

The while loop is another basic, very familiar loop. It’s a little more complicated than the for loop, but not by much. You can’t write it all on one line, but it’s about as simple as they come:

var i = 0; 

while(i < 10) { 
    // do stuff with i

As you can see, you have to initialize i outside the loop and then increment it inside the loop. That’s why this method isn’t quite as clean as the basic for loop. However, I think it’s a bit easier to understand, because it’s more broken up. Because of this broken up format, it’s possible to do a lot with while loops, as you’ll see shortly.

Note: You’ll want to make sure you do all your loop operations before you increment your iterator variable; otherwise, you risk skipping an iteration of your loop.

The quick n’ dirty while loop

This method is one of the shortest methods of writing a loop, and it’s probably one of fastest, too.

var i = 10; 
while(i--) { 
    // do stuff with i, which is in the range 9 to 0 

The reason this works and isn’t an infinite loop is that the while loop performs each iteration only when its condition evaluates to a truthy value (that is, anything that can’t be coerced into 0, or false). Since 0 is a falsy value, the condition evaluates to false and the loop performs its last iteration before exiting. Pretty neat, huh?

Using the while loop to iterate through an array

There are a few different ways to iterate through an array with a while loop, but they’re just slight variations of the previous while loops. Here’s the basic forward-iterating while loop:

// forward declaring our variables because that's recommended.
var len = things.length, 

while(i < len) {
    // do stuff with the current thing
    currentThing = things[i]; 
    // increment our counter 

As you can see, I cached the length of the array to speed up performance a micro-bit. Don’t do this if you’re modifying the length of your array inside the while loop. Instead, compare i to the length of the array every iteration.

And here’s the reverse while loop:

var i = things.length, 

while(i--) {
    // do stuff with the current thing 
    currentThing = things[i]; 

This is the preferred way to loop through an array if you’re going to use a while loop. Since it’s reversed, it doesn’t care if you’re modifying the length of the array or chucking elements in each iteration (as long as you aren’t modifying elements ahead of the loop, of course). You also don’t have to define as many variables, since we no longer need to cache the length of the array.

The do-while loop

The do-while loop is similar to the while loop in many ways, barring syntax. It’s a broken up loop in which you have to manually increment your variable. However, the key difference here is that the do-while loop executes the statement and then evaluates the provided condition, meaning the loop will execute at least once. Here’s what it looks like:

var i = 0;
do {
    // do stuff with i, which is in the range 0-9
    // remember, increment your counter at the very end of the loop 
} while (i < 10);

As you can see, not too different from the while loop, except for a little change in the syntax. The main difference is, even if the condition at the bottom evaluates to false, the loop will still run once:

var i = 0;

do { 
} while (i < -1); // still evaluates once

I haven’t really found a use for the do-while loop yet, so if you do, feel free to let me know what you did with it in the comments below. 😛

The Array.forEach loop

Array.forEach is a relatively new addition to the ECMA-262 standard, so it’s not seen a lot of use yet, nor do many older browsers support it. Nonetheless, there is a shim for it and it’s a remarkably useful function. Here’s some example usage:

var a = ["a", "b", "c", "d", "e"];

a.forEach(function(element, index, array) {
    console.log("Element: " + element + " at index " + index); 

As you can see, the syntax is quite simple. Simply call forEach on an array and pass in the function you want executed on each of the array’s elements. As I mentioned before, for browsers that don’t natively support forEach, there’s a shim (which can be found in Mozilla’s forEach documentation):

if ( !Array.prototype.forEach ) { 
    Array.prototype.forEach = function(fn, scope) { 
        for(var i = 0, len = this.length; i < len; ++i) {
  , this[i], i, this); 

Simply include the above code in your Javascript project and you’ll have full support for the forEach function. Although it really just serves as syntactic sugar to cover the for loop, you have to admit it is quite nice to have.

Object property loops

The object property loop is a way of looping over the properties of objects that aren’t arrays, since you can’t really use the normal for loop or while loop to loop through the elements of an object effectively. Here’s how it works:

var currentProp;

for(prop in obj) { 
    if(obj.hasOwnProperty(prop)) { 
        currentProp = obj[prop]; // do something with this property, where currentProp is the actual value 
                                 // you're looking at, and prop is the name of that value on the object. 

One of the things you need to make sure you do is check to make sure the property of the object you’re looping over actually belongs to that object and hasn’t come down the prototype chain. If you don’t do that, properties such as functions from the object’s prototype will become part of the loop. Not cool.

Another thing to be aware of is that the object won’t be looped over necessarily in the order that the properties are specified, nor even in the same order each time the properties are looped through. A plain object is not like an array in this respect, so you’ve got to be careful how you handle it.

Partial loop unrolling (and when not to use it)

Partial loop unrolling is a nice trick to have up your sleeve, especially if you’re working with large arrays (arrays with entries in the thousands or more). Basically, loop unrolling just means covering more than one element in each iteration of your loop. Here’s an example:

var currentThing;

for(var i = 0, len = things.length; i<len; i+=4) { 
    currentThing = things[i]; // do something with the current thing
    currentThing = things[i+1]; // do something with the next thing
    currentThing = things[i+2]; // do something with the next next thing
    currentThing = things[i+3]; // do something with the last next thing 

Since you’re effectively cutting your amount of iterations by half, or two thirds, or three quarters, or four fifths, or whatever amount you choose, it’s easy to see why this method should speed up your performance. However, interestingly enough, the gain you get by partially unrolling your loop isn’t that great. Therefore this isn’t a very effective method for speeding up your code until you’ve got arrays with elements numbering in the thousands (or higher).

Wrapping up

Well, that just about covers it for the most commonly used loops. I hope this helps, and, as always, If I’ve made any mistakes or typos, or if you just want to suggest something, feel free to leave me a note in the comments! Thanks for reading.

Oh, and as for fruit loops… do I really have to explain those? :-)

7 Cool JavaScript Expressions You Should Never Use

I think we can all agree that JavaScript is a pretty cool language. And as with many things, some bits of JavaScript are cooler than others. However, the cool-ness of a piece of JavaScript code is by no means synonymous with its practicality. In fact, one might go so far as to say that the coolness of a JavaScript statement is an inverse measure of how often it should be used. That is, the cooler the code is, the less you should use it.

And if that’s the case, then you should never, ever use anything you see in this article, because from here on out you will be exposed to some Seriously Cool Code.

1) Truncating numbers with bitwise operators

You can use bitwise operators to truncate numbers, like so:

num = ~~num;
num = num&num;
num = num|num;

Each of these is roughly equivalent to using parseInt or floor on a number, and will all yield the same result. They behave like Math.floor(num) would, assuming the number is positive. They always behave like parseInt(num, 10). Of the three, the last appears to be the fastest.

2) While loop with the iterator in the condition

// while loop with iterator as condition
var i = 5;
while(i--) {


This is a reverse for loop with what appears to be no conditional logic! Is it infinite? Nope. Since 0 is a falsy value, when i– results in zero, the loop will execute a final time and quit. It’s quick, easy, and the fastest loop currently known.

3) If statements without the if

someBoolean && (someStatement = 10);

Okay, what’s going on here? We’re taking advantage of the fact that when parsing conditional statements, the return value of the statement is evaluated. We also know that if the left hand statement of an && operator is evaluated as truthy, the right hand will be evaluated as well; otherwise, it won’t be. So this code is essentially equivalent to this:

if(someBoolean) {
someStatement = 10;

4) Comma operator

var a = 1,
b = 2;

b = (a++, 10);

The little known comma operator can be a bit mysterious and tricky to understand, but once you know what it means, it can be rather useful. Note, however, that useful is not equivalent with maintainable or understandable, and both of those take precedence over “useful”. Anyways, the comma operator performs all statements enumerated and returns the last statement’s value.

That means, in the above code, “a” will end up equaling 2, and “b” will end up equaling 10; the two statements in the last line are evaluated, and the return value of the last one is passed on.

5) The double exclamation point!!

value = !!value;

Using a double exclamation point will instantly identify you as an over-excited internet poster under-familiar with the colloquial usage of English. (unless you’re writing in JavaScript, in which case it’s perfectly ok). The double exclamation point, or double bang, converts a truthy or falsy value to “true” or “false”. In other words, it operates exactly like Boolean(value) would.

6) Define value if undefined

value = value || "hello world";

This function is quite simple. It defines a value if it appears to be undefined. That is, if the value already evaluates to a falsy value (which by some strange twist of fate, “undefined” does), it’s replaced by whatever comes after the OR operator. Note: the following is a much safer, but slightly longer, way of ensuring the same thing:

value = (typeof value !== "undefined") ? value : "hello world";

The above code checks to see if “value” is literally exactly equal to undefined, and will not fail if “value” does not exist anywhere in the code and is unrecognized in addition to being undefined. However, it is a mouthful. Or lineful, dare I add.

7) The void operator

undefined = void 0;

There is an operator called void. It evaluates whatever expression is passed to it and then returns a true, unadulterated value of undefined. This is useful in cases where you suspect that undefined may in fact have been defined at some point (and yes, that is legal in JavaScript). You can also compare directly against void 0 if you don’t want to overwrite whatever definition undefined has.

That’s all, folks!

I think that’s a sufficient amount of coolness in JavaScript for now, I don’t want to freeze anybody out. And, having read this article, keep in mind that you should never, ever use any of the code I’ve demonstrated for you above.

But, since I know you’ll ignore me, at least just remember to comment your super-cool JavaScript code. If not for yourself, at least for the sake of the next developer that comes along, who, being naturally less cool than you, will be unable to understand it.

And please, if you have any more cool, comment-worthy JavaScript, be sure to leave it below in the comments or shoot me an email–I’d love to see it.

How to Round Numbers To Arbitrary Values

This is just a quick little function I find pretty useful. It allows you to round any number to an arbitrary value, and can be useful for when you’re working with and rendering to a grid or want a slider that increments by a certain step.

if(typeof Math.roundTo === "undefined") {
    Math.roundTo = function(num, step) { 
        return Math.floor((num / step) + .5) * step; 

Math.roundTo(15, 10); // >> 20 
Math.roundTo(14.99, 10); // >> 10 
Math.roundTo(42, 1); // >> 42

As you can see, it’s pretty straightforward. Just pass in the number you want to round, and the step you want it rounded to and voilá, you’re good to go.

Field of view in Javascript using recursive shadow casting

Field of view, and stuff

Field of view, which involves determining which tiles are visible to the player, is a particularly fun aspect of writing roguelikes, in my opinion. When writing a field of view algorithm, you often find yourself trading quality for performance, or vice versa. Some algorithms get around this with a bit of trickery, like the Rogue algorithm. Other algorithms have no visible artifacts and in fact are quite pleasing visually, but pay for this with a definite decrease in performance.

There have been, of course, plenty of articles written about field of vision, and there is in fact an excellent compendium of resources over at Roguebasin (you can check that out here). This is a problem that has been thoroughly solved many times, beginning with Rogue’s rudimentary solution (you can see all the tiles in the room you’re in, but nothing else is visible; when in corridors, only the corridor tiles next to you are visible). The thing is, only a few Javascript algorithms (if any) are available to calculate FOV. Since I’m writing a Roguelike and have of course come up with an algorithm of my own, I have decided to remedy this lack of JS algorithms by sharing mine with you. It’s nothing fancy, but does provide a rather nice gradient falloff, which works in tandem with the display.js library that I previously posted.

Finding the happy medium

Many FOV algorithms have been written in an attempt to find the happy medium between performance and quality. After trying a few algorithms out, I eventually settled with recursive shadowcasting, which was both optimized for maximum performance but also very few artifacts. All in all, I’m happy with my choice. Here are some of the results you can get with recursive shadowcasting combined with a gradient falloff:

Demonstration of Saege's FOVMore Saege FoV

The field of view you see here is using a radius that is roughly double that of which is found in my game in order to better display the nice lighting falloff. However, even with aforementioned smoothed lighting, performance isn’t impacted in the slightest.

Has the happy medium been found?

As I’ve mentioned before, performance is usually achieved at the cost of quality. However, I was able to find a way to boost the performance of the algorithm without impacting quality. Now, to update the lighting, most algorithms clear the map of light and reset all the tiles to “unlit” or, depending on whether the player has already seen the tiles, “unseen”, which basically means the player has seen that tile at some point but can’t currently see it. The lighting algorithm then calculates the tiles within the player’s field of view and sets those tiles to “visible”, and the rendering engine displays them as lit up. Pretty straightforward.

The difference in my algorithm is that instead of clearing the entire map, it only sets to “unseen” those tiles which were lit the previous turn. This means that loads of CPU cycles aren’t wasted trying to reset the entire map’s lighting, most of which is outside the player’s field of view anyways. The algorithm simply appends each tile that is set to “visible” to an array, which is stored. When the lighting is next updated, those tiles in the array, and only those tiles, are set to “unseen” and the algorithm proceeds to calculate lighting as normal; wash, rinse, repeat, and you’ve got yourself one quick little field of view algorithm.

If you’ve stuck with me this long…

…you must be interested in seeing the algorithm. So, without further ado, here it is. It’s been sparsely commented, but hopefully should be of some help to some of you. And, as before, the LightSource class which contains the algorithm does make use of some external functions, which I will be introducing to you later on as progress on my game continues. And, before I forget, here’s a demo demonstrating its use.

Hopefully this article has given you something to think about, and, as always, feel free to comment and let me know if I’ve made any mistakes or typos!

Generating caverns with cellular automata

In this article, I’ll be discussing how to generate neat-looking fully connected caves using cellular automata. This algorithm builds off of another algorithm which can be found here. As noted, the linked algorithm is incomplete and cannot be used for generating dungeons that are suitable for a real roguelike. This article is about the method I used to make that algorithm workable.

First off, the basic algorithm:

To begin, let’s take a look at basic algorithm behind generating nice-looking cave levels with cellular automata:

1. Scatter wall blocks across the level at a 30-40% saturation level (I've found that 39% is ideal).

2. Iterate through all the tiles on the map four times: 
  - For each tile in each iteration, set the tile to be floor.
  - Then, calculate the number of wall tiles within both one square of the original tile (these are neighbors) and two squares (these tiles are nearby). Store these numbers.
  - If the number of neighbors for the tile is greater than or equal to 5, or there are less than two wall tiles nearby, set this tile to be a wall.
  - If it is not a wall already, leave this tile as a floor tile. 3. Iterate through all the tiles on the map three more times:
  - For each tile in each iteration, set the tile to be floor.
  - Calculate the number of wall tiles within both one square of the original tile.
  - If this tile has five or more neighboring walls, make it a wall. Otherwise, leave it as a floor tile.

The issue with cellular automata is…

…the caves generated with the cellular automata technique are often unconnected. Since many roguelikes depend on all parts of a level being accessible, this is usually a bad thing. So, clearly, we need a way to drop the disconnected regions or otherwise ignore them. The best way to do this is with a flood fill algorithm. A flood fill algorithm is able to find all the nodes connected to each other that aren’t delimited by another type of node. In graphics applications, this is usually used to find regions of similar color.

In our algorithm, the flood fill algorithm will be used to find all the regions of the cave that are comprised of purely floor tiles–in other words, all the caverns (unconnected or not) on the map. Once we have a list of the caverns, we can select the largest cavern–this will be the main cavern. We can then simply drop the other patches, as they are small unconnected regions that are precisely what we don’t want.

Flood fill algorithm in Javascript:

Here’s how I managed the flood fill algorithm and subsequent cavern managing in Javascript:

// this variable will be used to store the various unconnected caverns 
var caverns = [];

// begin looping through the map
for (var x = 1; x < this.size.x; x++) {
for (var y = 1; y < this.size.y; y++) {
var cavern = [];
var totalCavern = [];

if ([x][y].type != "dirty floor") { // we've already been over this tile or it is already part of a cavern,
// no need to check it


while (cavern.length > 0) {
var n = cavern.pop();

if (n.type == "dirty floor") { // set a flag on the tile indicating it has already been checked

for (var i = 0; i < 8; i++) {
var curTile =[n.position.x + x_array[i]][n.position.y + y_array[i]];
if (curTile.type == "dirty floor") {

// add this cavern

// sort the caverns
caverns.sort(function (a, b) {
return (b.length - a.length);

// remove the largest cavern, as it is the main cavern

// now that we've got the unconnected caverns, change their tile type
if (caverns.length > 0) {
for (var i = 0; i < caverns.length; i++) {
for (var j = 0; j < caverns[i].length; j++) {

As you can see, I loop through all the tiles. First, I check to see if I’ve already been over the tile; if so, I pass it on. If I haven’t, I go through that tile and search its neighbors, too. Eventually, I’ve searched all the tiles on the map and sorted them into the various caverns to which they belong. Once I’ve done that, I sort the caverns by size, from largest to smallest, and pick out the one with the most tiles in it (in other words, the biggest cavern). This is the main cavern, so we can get rid of or ignore the rest. I personally chose to get rid of my unconnected caverns, but it’s possible to connect them or just ignore them for the rest of the dungeon generation code–it’s up to you really.

In finis…

If you’ve read this far, you’re at least slightly intrigued by the cellular automata/flood fill cave generation algorithm–good! Hopefully you’ll have as much fun playing around with it as I did. As you can see, the Javascript code I included above makes heavy use of some external data-managing structures, such as a map data structure and a tile structure as well; I’ll be writing more articles about how I handle the map and tile stuff later. As always, thanks for the read, and if I made any mistakes during this article or if any of my code can be improved, please let me know!

Console-like display in the browser?

I’ve been working for some time on a Roguelike in Javascript. One of the first things I had to do for my Roguelike, of course, was establish some sort of display routine. I could have gone with HTML5’s new <canvas> tag or something similar, but setting up a console-like environment for canvas can get a little involved. So instead, I established a way to use the browser’s native text rendering. Say hello to a simple Javascript class for console-like rendering in the browser: I call it display.js.

So, let’s take a look at the code required initialize a basic 80 by 25 console and draw a few characters with the display class:

// create a display for console-like rendering
display = new Display(new Vector2(80, 25), new Vector2(10, 35), true);

// let's draw the classic @ sign:"@", new Vector2(10, 10));

// maybe fake a few walls
for(var x = 0; x<10; x++) {"#", new Vector2(x, 0));

// let's put a green slime down, too"j", new Vector2(15, 15), "green");

Okay, let’s step through this code really quickly. Before we begin, though, I’d like to note the Vector2 class I use here; it’s nothing more than a utility function I use to hold a position with X and Y values (you can grab a copy of it here). So, in the code, the first line initializes the console display. The first variable we pass in to this function call is the size of the display–I use 80 by 25 because that’s a standard console size, but these numbers could be anything you want. The second variable we pass in is the offset of the console from the rest of the page. The third variable we pass in is whether we want this display to open in a new window or not. If you set it to false, the display will simply be written to your HTML page. If it’s set to true, the console will open in a popup window.

The next line calls a function on our newly created console, namely ch. This allows you to display a character on the screen and takes a minimum of two and up to five parameters. In order, these are: the character to display, the position of that character, the color of the character, the opacity of the character, and the background color of the character. Only the character you want to write and the position of that character are required; the others are optional. The color variable accepts a few basic color names as well as hex values. The next few lines do nothing more than demonstrate the various applications of the ch function, which is the only function display.js makes use of.

In finis…

As you can see, the display class isn’t very advanced right now, but it’s been all I’ve needed so far. If you want to download the class, you can grab it here. Quick note, it does make use of jQuery, so make sure you include that in your project before you attempt to use it. As progress on my game continues, this library will likely be updated with more functions as I need them. Thanks for taking a look, and be sure to keep an eye on Hey Javascript for more updates in the near future! (hopefully, I’ll be posting some dungeon generation algorithms in Javascript soon)

Roguelike game programming and development in Javascript?

The Roguelike genre has been in development for decades–since 1980, in fact, when Rogue, the first Roguelike game, was written. Since then, Roguelike games have been created in many different programming languages. Among the more popular of these languages are C, C++, Java, and Python. However, a new contender is appearing: Javascript. Although it’s the new kid on the block, Javascript is quickly becoming a popular choice for Roguelike development and has already been used to make quite a few games.
Continue reading Roguelike game programming and development in Javascript?

8 great A* pathfinding resources

If you’re writing a game that incorporates both a terrain of some sort and enemies that walk around, the chances are you’ll need some version of pathfinding to control the enemy movement patterns. The thing is, pathfinding is serious business–it’s not easy to grasp. To make things worse, there aren’t many good pathfinding resources–most of the articles that turn up on Google and such only serve to confuse you further. That’s why I’ve taken the time to compile this list of pathfinding resources that I’ve found to be actually helpful, as opposed to confusing or just plain wrong. Enjoy!
Continue reading 8 great A* pathfinding resources

A revolutionary and amazing new way to loop through arrays

…well, revolutionary and amazing to me, anyhow. Like most Javascript programmers, I usually use a for loop to iterate through my arrays, a method which typically works pretty nicely and doesn’t really have many drawbacks. However, I recently discovered another method which takes a tad less typing while maintaining the same functionality–the forEach loop. It’s quite handy and you don’t have to declare a bunch of variables to loop through an array.

The forEach loop behaves pretty much like your standard for loop, except that it’s a function that you call only on arrays. It looks like this:

myArray.forEach(function(element, index, array) {
console.log(element); // element is the current element in the array
console.log(index); // index is the position of that element in the array
console.log(array); // this is the array the forEach loop was called on

The above code passes an anonymous function into the forEach method, but you can use any function you want. Within that function, element refers to the current element in the array, index is the index of the current element of the array, and array is the array the forEach function was called on (note: you don’t have to pass in all the variables; just make sure you pass them in in the correct order). The forEach loop is a pretty handy alternative to the standard for loop and something I’ll definitely be turning to in the future.

The only drawback is that the forEach loop is relatively new, so you’ll have to provide a fallback for older browsers if you’re worried about compatability. Mozilla’s documentation provides an extensive article on the forEach loop and elaborates on a method to provide that fallback for older browsers I was talking about earlier.