D Dev Notebook

JavaScript JSON loop

JS

In JavaScript, loops are used to repeatedly execute code. They are helpful when you want to run the same code many times, with different values or until a condition is met.

1. for Loop

Used when you know how many times you want to repeat the loop.

// loop from 0 to 4
for (let i = 0; i < 5; i++) {
    console.log("Number:", i);
}
//output
Number: 0
Number: 1
Number: 2
Number: 3
Number: 4

2. while Loop

Repeat code as long as the given condition is true.

let count = 0;

// loop until count reaches 3
while (count < 3) {
    console.log("Count is:", count);
    count++; // increment count
}
//output
Count is: 0
Count is: 1
Count is: 2

3. do-while Loop

Similar to while, but guarantees at least one execution, as it checks the condition afterward.

let num = 0;
do {
    console.log("Current number:", num);
    num++;
} while (num < 3);
//output
Current number: 0
Current number: 1
Current number: 2

4. for...of Loop

Convenient for looping through arrays (or any iterable).

const fruits = ['apple', 'banana', 'orange'];

for (const fruit of fruits) {
    console.log("Fruit:", fruit);
}
//output
Fruit: apple
Fruit: banana
Fruit: orange

5. for...in Loop

Used to loop over the keys (property names) of an object.

const person = { name: 'Alice', age: 25, city: 'London' };

for (const key in person) {
    console.log(key + ":", person[key]);
}
//output
name: Alice
age: 25
city: London

Loops in JavaScript provide several key benefits:

1. Avoids Code Repetition:

Loops prevent you from writing the same lines of code multiple times.

2. Efficiency & Productivity:

Loops help you write less and achieve more. They automate repetitive tasks, making your code shorter and clearer.

3. Easy to Maintain:

Updating looped code is simpler because changes in a single loop affect every iteration.

4. Scalability:

Loops allow easy handling of large data sets. For example, iterating through an array of hundreds or thousands of items becomes effortless.

5. Dynamic Operations:

Loops adapt dynamically to changing conditions or data, useful for tasks like iterating until a certain condition is met (e.g., while loops).

  • Less repetitive and cleaner code.
  • Saves time and improves efficiency.
  • Easy code maintenance and updates.
  • Dynamically handles changing data.
  • Scalable for handling larger tasks and data.

On this page