Javascript
Loops are programming constructs that allow us to repeat a set of instructions multiple times. They are essential for automating tasks and iterating over data.
For Example;
console.log("Hello, World!");
console.log("Hello, World!");
console.log("Hello, World!");
console.log("Hello, World!");
console.log("Hello, World!");
This code will print Hello World!
5 times, now we can use For loop to print it.
for (let i = 0; i < 5; i++) {
console.log("Hello, World!");
}
There are 4 types of loops in JavaScript
The for
loop is the workhorse of iteration in JavaScript. It consists of three components: initialization, condition, and increment/decrement.
Here’s a simple example:
for (let i = 0; i < 5; i++) {
// Your code here
}
The while
loop repeats a block of code as long as a specified condition is true. It’s great for situations where you don’t know the exact number of iterations beforehand.
Here’s a simple example:
let count = 0;
while (count < 5) {
// Your code here
count++;
}
Similar to the while
loop, the do-while
loop executes the code block first and then checks the condition. This ensures that the block of code is executed at least once.
Here’s a simple example:
let x = 0;
do {
// Your code here
x++;
} while (x < 5);
The for-in
loop is specifically designed for iterating over the properties of an object. It provides a concise way to access key-value pairs.
Here’s a simple example:
const myObject = { a: 1, b: 2, c: 3 };
for (let key in myObject) {
// Your code here, using myObject[key]
}
Now that we’ve covered the fundamental loop structures, let’s briefly touch on other loop types that can enhance our code
The for-of
loop is used to iterate over iterable objects such as arrays and strings. It simplifies the process of accessing individual elements.
Here’s a simple example:
const myArray = [1, 2, 3, 4, 5];
for (let element of myArray) {
// Your code here, using 'element'
}
Nested loops involve using one loop inside another. This technique is powerful for dealing with multidimensional data structures.
Here’s a simple example:
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
// Your code here
}
}