DEV Community

Cover image for Repetition can make you loopy!: Intro to JavaScript Loops
Daniel J
Daniel J

Posted on

Repetition can make you loopy!: Intro to JavaScript Loops

Looping is a concept utilized in most programming languages we use today. The idea behind it is central to what we strive for as programmers, that being minimizing our workload as much as humanly possible. Focusing in on that idea, we can point to the D.R.Y. principle, otherwise known as "Don't Repeat Yourself," originally coined in "The Pragmatic Programmer". After all, why repeat yourself when the computer can do it for you! In this discussion, I'll go over looping in the context of JavaScript with examples using JavaScript and p5js. However, keep in mind that the concept is largely transferrable across other languages that utilize loop structures.

So what is a loop?

A loop is a block of code that performs an action for us a specified - or sometimes unspecified - amount of times. The possibilities become endless with loops, allowing us to create complex programs and avoid Carpal Tunnel Syndrome. JavaScript has a few different loop methods at its disposal, but we'll be going over the 3 most common that you'll come across:

  1. For loops
  2. For.. in loops
  3. While loops

For loops

A for loop will loop through a collection of data, declaring a starting point, an ending point and an incrementation. The syntax in a for loop looks like this:

array [1, 2, 3, 4, 5]

       start          end      increment      
         |             |           |
for (let i = 0; i < array.length; i++) { //be sure to separate by ;
    //do something here
    console.log(array[i])
};
Enter fullscreen mode Exit fullscreen mode

console will log
1
2
3
4
5

Lets break down this code to better understand what's going on under the hood.

  1. We begin the loop with the for keyword, (who would've thought!) before opening up a parentheses to begin our chain of logic.
  2. Our starting point is declared with variable keyword declaration let or var. (IMPORTANT: You can use const but remember it cannot be reassigned.) I prefer using let, and in JavaScript, using i as the name of the variable in a for loop is a common naming convention, but it can be anything your heart desires!
  3. So, we've initiated our for loop. We've told the computer that we want the variable i to be 0 at the start of the loop. Now, we want to tell it when to stop. Once again, this stopping point can be anything you want it to be. However, for this example, we're using the .length array prototype method to indicate that we want the loop to end at the last index of the array. Fun tip about the .length method: using .length allows us to make this loop flexible with an array whose quantity may increase or decrease throughout the program.
  4. Lastly, we want to indicate our increment amount, which again can be anything! In my above example, I used the ++ operator to indicate i+1.

Now let's see an example with different start and stop points, as well as iteration by iteration.

for (let i = 0; i < 10; i ++) {
 console.log(i);
};
iteration 1: i=0, 0 is < 10 incr by 1 and log the iteration's value(0)
iteration 2: i=1, 1 is < 10 incr by 1 and log the iteration's value(1)
etc.. 
console will log numbers 1 - 9 as when i = 10 it is no longer less than 10.
Enter fullscreen mode Exit fullscreen mode

For...in Loops

For...in loops are used to loop through an object's properties to achieve the same result, but for objects! The syntax for a for...in loop looks like this:

let car = {
manufacturer: 'BMW',
wheels: 4,
doors: 2
year: 1985
};
for (let key in car) {
console.log(key, car[key])
};
Enter fullscreen mode Exit fullscreen mode

The expected output for the above code to the console log would be:

manufacturer BMW
wheels 4
doors 2
year 1985

Let's break it down like an old BMW!

  1. We start off with our for keyword before opening up some parentheses to declare our variable for the keys in object.(foreshadowing!)
  2. Next, using a variable declarer of your choice like let, we declare the name we want that variable to have, one of the most common naming conventions being key/keys.
  3. Here's where that in keyword shines! We use it to tell our computer where to check, that being in the object that is declared after.
  4. The final piece of the puzzle is the object we're looping through. In the above example, it's the car object.

While loops

While loops are probably my least favorite kind of loop. It can excel with small looping quantities and smaller scale programs, but otherwise it's usually not recommended. This loop essentially works by telling the computer to execute some task while x condition is true. The syntax for a while loop looks like this:

let i = 0;

while (i < 10) {
console.log(i);
i++;
}
Enter fullscreen mode Exit fullscreen mode

Lets break it down, one last time!

  1. The syntax for this code is pretty straightforward. Outside of the while loop, we declare a variable i and assign it to 0. This is the setup for our while loop that works based off a certain condition remaining true.
  2. We then use the while keyword to start off, before starting our conditional logic. Here we will say while i is less than 10, we want some block of code to be executed.
  3. Lastly, and arguably the most important part about this loop, is the incrementation of i that occurs on the last line of the code block. We need to increment i as if we do not, we will create an infinite loop, since i will remain 0 infinitely.

I'm sure by now, you're able to see the utility loops can provide us in our programs. We can pass in collections of data to retrieve information, repeat executable code as much as we want, and stay true to our D.R.Y. principle.

Visual examples through p5js

In this last section, I'll be creating some visual examples to show how helpful loops can be. I'll be using p5js, a JavaScript library with functionality for creative coding. That being said, I'll try to give a condensed version of the functions being utilized in the following examples.

function setup() {
  createCanvas(800, 600);
  background('beige');
}

function draw() {
  translate(width / 2, height / 2);
  rectMode(CENTER);
  noFill();
  rect(0, 0, 400, 400);
  noLoop();//this function is to stop the draw func from looping
Enter fullscreen mode Exit fullscreen mode

This block of code renders a canvas that is 800x600 pixels, and draws a rectangle in the cartesian coordinates (0, 0) and a width and height of (400, 400). It looks like this:

Beige Canvas with Rectangle in middle

Now I want you to imagine you have to draw 100 rectangles on this canvas at random x and y coordinates, with random width and height arguments (between 0 and 10) and you have no idea that loops exist (or recursion!). The code would look something like this:

function draw() {
  noFill();
  rect(random(width), random(height), random(10), random(10));
  rect(random(width), random(height), random(10), random(10));
  rect(random(width), random(height), random(10), random(10));
  rect(random(width), random(height), random(10), random(10));
  rect(random(width), random(height), random(10), random(10));
  rect(random(width), random(height), random(10), random(10));
  rect(random(width), random(height), random(10), random(10));
  rect(random(width), random(height), random(10), random(10));
  rect(random(width), random(height), random(10), random(10));
  rect(random(width), random(height), random(10), random(10));
  rect(random(width), random(height), random(10), random(10));
  rect(random(width), random(height), random(10), random(10));
  rect(random(width), random(height), random(10), random(10));
  rect(random(width), random(height), random(10), random(10));
  noLoop();
}
Enter fullscreen mode Exit fullscreen mode

The sketch would look something like this:

beige background p5js sketch with 14 random placed rect

Which is fine and dandy but I stopped after 14 pastes, and you can imagine how painful 100 would be.

Now lets actually draw 100 rectangles of the same arguments using a for loop.

function draw() {
//I removed the translate func to allow it to start from the top left of the screen
  noFill();
  for (let i = 0; i < 100; i++) {
  rect(random(width), random(height), random(10), random(10));
  noLoop();
  }
Enter fullscreen mode Exit fullscreen mode

Which produces an image similar to this:

Beige background p5js sketch with 100 rectangles randomly placed and sized
We can go as far as our computer's strength can take us!
The same loop but with 5,000 rectangles:

beige bg 5k rect random size and placement

This truly puts into perspective how powerful loops can be. That single loop can cut down a theoretically infinite number of lines of typing that same function in less than 5 lines. You can read more about p5js functionality to fill in the bits of information on native p5js functions, as well as the Mozilla Developer Docs to get more information on loops.

Top comments (0)