A Developer’s Guide to JavaScript Looping: Techniques and Best Practices

Gaurav Rathee
Nerd For Tech
Published in
7 min readOct 12, 2023

In this article, we will talk about the most basic concept of programming i.e loops. Loops offer a quick and easy way to do something repeatedly and are used to perform repeated tasks based on a condition. you will find the loops in almost all programming languages.

Why do we need loops?

Loops are control structures used to repeat a given section of code a certain number of times or until a particular condition is met. Also, we can repeat to infinity times as well. let’s understand this with an example:

Suppose we need to add 1 to number 10 times

var sum = 0;
sum = sum + 1;
sum = sum + 1;
sum = sum + 1;
sum = sum + 1;
sum = sum + 1;
sum = sum + 1;
sum = sum + 1;
sum = sum + 1;
sum = sum + 1;
sum = sum + 1;
console.log(sum); // output sum = 10;

In the above scenario, A developer has to write 1o lines of repeated code to achieve this simple scenario. Let’s try to achieve this using loop

var sum = 0;
for (var i = 0; i < 10; i++) {
sum = sum+1;
}
console.log(sum); // output sum = 10;

the above-mentioned code can be used to perform the same repetitive task with fewer lines of code.

Type of loops

JavaScript supports different kinds of loops:

  • for/in - loops through the properties of an object
  • for/of - loops through the values of an iterable object
  • while - loops through a block of code while a specified condition is true
  • do/while - also loops through a block of code while a specified condition is true
  • for - loops through a block of code a number of times

FOR loop

The JavaScript for loop iterates the elements for a fixed number of times. Mostly, it should be used if the number of iteration is known. The for loop has the following syntax:

for (statement 1; statement 2; statement 3) {
// code block to be executed
}

Statement 1 (initialization statement) is executed (one time) before the execution of the code block.
Statement 2 (condition) defines the condition for executing the code block.
Statement 3 (update statement) is executed (every time) after the code block has been executed.

for (initialization statement; condition; update statement) {
// code block to be executed
}

Let’s understand the working of for loop with the flow diagram

For loop will keep on iterating the statement until the condition is not met. let us analyze the working of FOR loop in steps:

Step 1: Initialization statement is executed
Step 2: Condition check will be executed
Step 3: If the condition is true, it will execute the statement. If the condition is false, go to step 6
Step 4: Update statement is executed
Step 5: Go to step 2
Step 6: Exit

While loop

The JavaScript while statement creates a loop that executes a block of code as long as the test condition evaluates to true. The condition is evaluated before executing the statement.

while (condition) {
code block to be executed
}

Let’s understand the working of While loop with the flow diagram

Let me explain each part of the flowchart:

Step 1: Initialization: This is where you initialize any variables 
or values that will be used in the loop.
Step 2: Condition: This is the condition that is evaluated before each
iteration of the loop. If the condition is true, the loop continues
if false, the loop exits.
Step 3: Execute Code: Here, you place the code that should be executed as
long as the condition is true. This is the block of code that
repeats until the condition becomes false.
Step 4: Update Variables: Within the loop, you may need to update variables
or values to ensure that the condition will eventually become false
and the loop will terminate.
Step 5: Exit Loop: This is where the loop ends when the condition becomes
false.

Be cautious when using while loops, as they can potentially result in infinite loops if the condition is never met. To avoid this, make sure that your condition will eventually evaluate to false to prevent the script from running endlessly.

do/while loop

A do/while loop in JavaScript is another type of loop structure similar to a while loop. The key difference is that in a do/while loop, the code block is executed at least once before checking the loop condition.

Here’s the basic syntax:

do {
// Code to be executed at least once
} while (condition);

In a do/while loop, the code block is executed first, and then the condition is checked. If the condition is true, the loop continues, and the code block is executed again. The loop continues to run as long as the condition remains true.

Use do/while loops when you need to ensure that a certain piece of code runs at least once, regardless of the condition, and then continue to repeat if the condition is met.

Let’s understand the working of do/while loop with the flow diagram

Let me explain each part of the flowchart:

Step 1: Execute Code: The code block is executed first, unconditionally,
before checking the loop condition.
Step 2: Update Variables: Inside the loop, you may need to update variables
or values to determine if the loop should continue.
Step 3: Condition: After executing the code block, the condition is checked
If the condition is true, the loop continues, and it goes back to
executing the code block, updating variables, and checking the
condition again. If the condition is false, the loop exits.
Step 4: Exit Loop: When the condition becomes false, the flow moves to the
"Exit Loop."

for/in loop

The for...in loop in JavaScript is used to iterate over the properties of an object. It's specifically designed for looping through the keys (or property names) of an object. Here's the basic syntax:

for (key in object) {
// Code to be executed for each property in the object
}

Here’s an example of how you can use a for...in loop to iterate through the keys of an object:

const person = {
firstName: "Gaurav",
lastName: "Rathee",
age: 30,
};
for (let key in person) {
console.log(key + ": " + person[key]);
}
for (let key in object) {
if (object.hasOwnProperty(key)) {
// Code to be executed for each own property in the object
}
}
This ensures that you only loop through the object's own properties
and not those inherited from its prototype chain.

It’s important to note that for...in loops are typically used for objects, not for arrays. When working with arrays, it's often better to use a for loop or the forEach method.

be cautious when using for...in loops with objects, especially if you're working with objects that inherit properties from their prototypes. To avoid iterating over inherited properties, you can use the hasOwnProperty method

for/of loop

The for...of loop in JavaScript is used to iterate over the values of iterable objects, such as arrays, strings, maps, sets, and more. It provides a more convenient way to loop through the elements of an iterable object compared to the traditional for or for...in loops. Here's the basic syntax:

for (variable of iterable) {
// Code to be executed for each value in the iterable
}

Here are a few examples of how to use the for...of loop:

  1. Iterating through an array:
const colors = ['red', 'green', 'blue'];

for (const color of colors) {
console.log(color);
}

2. Iterating through a string (treating it as an iterable of characters):

const text = 'Hello';

for (const char of text) {
console.log(char);
}

3. Iterating through a Set:

const mySet = new Set([1, 2, 3]);

for (const value of mySet) {
console.log(value);
}

4. Iterating through a Map (which provides both key and value):

const myMap = new Map([
['a', 1],
['b', 2],
['c', 3]
]);

for (const [key, value] of myMap) {
console.log(key, value);
}

The for...of loop simplifies iteration and is the preferred choice when working with iterable objects. It automatically handles the details of iterating over the elements, and it's often more readable than other looping constructs.

If you like this article press 👏 the clap button 1000 times or as many times as you want. Feel free to ask a question if you have any. Thanks a lot for reading!

Before You Go

Thanks for reading! If you want to get in touch with me, feel free to reach me at gauravrathee0@gmail.com or my LinkedIn Profile. Also, feel free to explore my profile and read different articles.

--

--

Gaurav Rathee
Nerd For Tech

I write about my learnings in the field of computer science i.e application development , Data science, Artificial Intelligence etc