Javascript Loops & Iterations Cheat Sheet – Simple Examples

Welcome to a beginner’s tutorial on Javascript loops and iterations. Want to loop through arrays, objects, or do things repetitively?

The common mechanisms to loop and iterate in Javascript are:

  1. For – for (let i=0; i<10; i++) { ... }
  2. For-In – for (let key in object) { ... }
  3. For-Of – for (let element of array) { ... }
  4. Foreach – array.foreach((element) => { ... });
  5. While – while (i<10) { i++; }
  6. Do-While – do { i++; } while (i<10);
  7. Break – while (i<10) { if (i<0) { break; } i++; }
  8. Continue – while (i<10) { if (i==2) { i+=2; continue; } i++; }

That covers the quick basics at a glance, but let us walk through examples of each – Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TABLE OF CONTENTS

Download & Notes Loops & Iterations Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

INFOGRAPHIC CHEAT SHEET

Javascript Loop Cheatsheet (click to enlarge)

 

 

JAVASCRIPT LOOPS & ITERATIONS

All right, let us now get into the examples of loops and iterations in Javascript.

 

1) FOR

1-for.js
/// (A) INCREMENT
for (let i=1; i<=3; i++) {
  console.log(i); // 1, 2, 3
}
 
// (B) DECREMENT
for (let i=3; i>=1; i--) {
  console.log(i); // 3, 2, 1
}

// (C) LOOP ARRAY
var arr = ["a", "b", "c"];
for (let i=0; i<arr.length; i++) {
  console.log(arr[i]); // a, b, c
}

// (D) WE CAN ACTUALLY OMIT ALL INIT & CONDITIONS
var i = 0;
for (;;) {
  i++;
  console.log(i);
  if (i==2) { break; }
}

The for loop is one of the most commonly used, and some books don’t even explain it right. Take note that there are “3 segments” – for (INITIALIZE; END CONDITION; STEP).

  • INITIALIZE This runs before the loop starts.
  • END CONDITION The condition to stop looping, this statement must resolve to a boolean true/false. Runs after INITIALIZE and after every cycle.
  • STEP Run this after every cycle.

Yes, we can leave all 3 empty… But that will not make any sense.

 

2) FOR-IN

2-for-in.js
// (A) ITERATE OBJECT
var person = {
  name: "Jon Doe",
  email : "jon@doe.com"
};
for (let key in person) {
  // name - Jon Doe, email - jon@doe.com
  console.log(`${key} - ${person[key]}`);
}

// (B) ITERATE ARRAY
var animals = ["Birb", "Cate", "Doge"];
for (let i in animals) {
  // Birb, Cate, Doge
  console.log(animals[i]);
}

// (C) ITERATE STRING
var hello = "world";
for (let i in hello) {
  // 0, 1, 2, 3, 4
  console.log(i);
}

The for-in loop will run through the enumerable properties (keys) of an object, in particular:

  • The index of arrays.
  • Character position of a string.
  • Properties (keys) of an object itself.

 

 

3) FOR-OF

3-for-of.js
// (A) ITERATE ARRAY
var animals = ["Birb", "Cate", "Doge"];
for (let element of animals) {
  // Birb, Cate, Doge
  console.log(element);
}

// (B) ITERATE STRING
var hello = "world";
for (let char of hello) {
  // w, o, r, l, d
  console.log(char);
}

// (C) ITERATE OBJECT - ERROR, NOT ITERABLE
var obj = { "foo" : "bar" };
for (let value of obj) {
  console.log(value);
}

This should be pretty self-explanatory by now, for-in iterates the properties, for-of iterates the values (data) themselves.

 

4) FOREACH

4-foreach.js
var animals = ["Birb", "Cate", "Doge"];
animals.forEach((element, index) => {
  console.log(element);
  console.log(index);
});

The forEach() function only applies to arrays – It loops through the elements within the array.

 

 

5) WHILE

5-while.js
var animals = ["Birb", "Cate", "Doge"],
    i = 0;
while (i < animals.length) {
  console.log(i); // 0, 1, 2
  console.log(animals[i]); // Birb, Cate, Doge
  i++;
}

A while loop is pretty simple – It will continue to run until the provided condition (i < animals.length) turns false… But beware, a common mistake that many newbies make is an end condition that will never be met, ending up in an infinite loop.

 

6) DO-WHILE

6-do-while.js
var animals = ["Birb", "Cate", "Doge"],
    i = 0;
do {
  console.log(i); // 0, 1, 2
  console.log(animals[i]); // Birb, Cate, Doge
  i++;
} while (i < animals.length);

Look no further, this does almost the exact same thing as while. What is the difference here?

  • while will not even start if the condition is not met.
  • do-while will run at least once, even when the condition is not met.

 

7) BREAK & CONTINUE

7-break-continue.js
let i = 0;
while (i>=0) {
  // (A) CONTINUE - SKIP TO NEXT CYCLE
  if (i==2) {
    i+=2;
    continue;
  }
  i++;
  console.log(i); // 1, 2, 5, 6

  // (B) BREAK - STOP CYCLE
  if (i==6) { break; }
}

Lastly, we have another 2 Captain Obvious mechanisms:

  • continue Skip the current cycle.
  • break Stop the entire loop. Works in for for-in for-of foreach too.

 

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

SUMMARY & CHEAT SHEET

Method/Statement Description
for (INIT, CONDITION, INCREMENT) { STATEMENTS } Evaluates a given condition and keeps running until the condition becomes false.
for (VARIABLE in OBJECT) { STATEMENTS } Will loop through the enumerable properties of an object.
for (VARIABLE of OBJECT) { STATEMENTS } Will loop through the data of an iterable object.
ARRAY.forEach (FUNCTION); For arrays only, will loop through each of the array elements with the given function.
while (CONDITION) { STATEMENTS } Will keep on running the loop until the condition is false.
do { STATEMENTS } while (CONDITION) Same as while, but will run through the statements at least once, then check the condition.
break; Breaks and stops the loop.
continue; Will skip the current iteration, and start the next one.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published.