1. javascript
  2. /basics
  3. /loops

The Basics of JavaScript Loops

Getting Started

Have you ever been in a situation where you needed to perform a task multiple times, but you didn't want to manually do it over and over again? Loops are an essential part of control flow in JavaScript and provide a way to automate repetitive tasks.

As a programmer, you're tasked with creating logic that makes sense for computers to follow. It's not always a straightforward process, and you may find yourself repeating steps or checking conditions frequently. This is where control flow comes into play, and loops are a crucial component of it. Loops are used to execute a block of code multiple times based on a condition. In JavaScript, there are several types of loops, each serving a slightly different purpose.

The For Loop

As a common control flow statement, the for loop allows us to repeat a block of code a specified number of times.

Let's see how the syntax looks and explain it in a bit more detail.

for (initialization; condition; increment/decrement) {
  // code to be executed
}

For the sake of understanding each part, we'll use a basic example that will print the numbers from 0 to 9:

for (let i = 0; i < 10; i++) {
  console.log(i);
}
// Output: 0 1 2 3 4 5 6 7 8 9

First, we initialize a variable let i = 0. Then, the condition i < 10 is checked before each iteration of the loop. As long as this is true, the increment i++ adds 1 to i after each iteration.

The for...in Loop

We can use this loop to iterate over the properties of an object. It's a convenient way to access each property in an object without having to write separate code.

Now, using the for...in statement we'll print the key-value pairs of the object with a bit of template literals magic. Like so:

const obj = {
  name: "John",
  age: 30,
  job: "developer"
};

for (const prop in obj) {
  console.log(`${prop}: ${obj[prop]}`);
}
// Output:
// name: John
// age: 30
// job: developer

The initialization starts in for (const prop in obj) where prop acts as our temporary variable that holds the property name during each iteration of the object. It accesses each property's name using prop, and its value using obj[prop]. Finally, the output neatly logs the property name and value to the console using template literals.

The for...of Loop

With this statement, we're able to go over the values of an iterable object. We'll cover other uses in our additional resources but for now, let's take a look at a use case where we print the values of an array.

const arr = [1, 2, 3, 4, 5];

for (const val of arr) {
  console.log(val);
}
// Output:
// 1
// 2
// 3
// 4
// 5

First things first. Our loop starts by initializing val with the first element in the array. Then, it runs for each subsequent element in the array until all elements have been processed. Lastly, we log each element in the array to the console and we get an output of the numbers 1 to 5, each being on a new line.

The While Loop

The while loop is relatively simple and will execute a block of code as long as the condition we specify is true. Now, let's demonstrate.

let i = 0;
while (i < 5) {
  console.log("The number is " + i);
  i++;
}
// Output:
// The number is 0
// The number is 1
// The number is 2
// The number is 3
// The number is 4

We start with a simple variable, i, initialized to 0. As long as i is less than 5, the loop runs, printing what we concatenated each time with i increasing by 1 on each iteration. Eventually, when it reaches 5, the loop comes to a close.

The do...while Loop

The do...while statement is similar to the while loop, but with one key difference: the code inside it will always be executed at least once before the condition is checked and it'll continue to run as long as the condition we stated is true.

let i = 0;
do {
  console.log(i);
  if (i % 2 === 0) {
    console.log(i + " is even");
  }
  i++;
} while (i <= 10);

Initially, the code block is executed once before the condition i < 10 is checked, and will continue to run as long as i is less than 10. We add a bit more control flow with the if statement that checks if i is even, and if so, it prints a message to the console.

The Break Statement

We use the break statement to prematurely exit loops. Furthermore, it stops the execution if the condition we specified is met. For instance, if we have a loop that's counting to 10 and we want to exit it once the count reaches 5, we can use a break statement. Like so:

for (let i = 0; i < 10; i++) {
  if (i === 5) {
    break;
  }
  console.log(i);
}

After it finishes, it'll print the numbers from 0 to 4 to the console.

Final Thoughts

Loops have a range of applications in JavaScript. They're a must-have for optimizing code, especially when dealing with arrays, objects, or repetitive tasks.

We've only covered the various basic forms as well as their appropriate usage. However, this is just an introduction and there's much more to be explored in the realm of loops in JavaScript. Feel free to check out some of the more in-depth resources provided in each section.

Useful Resources

Expand your JavaScript knowledge on loops and browse some extra code snippets.