Day 9 of #100daysofjs

For Loops in JavaScript

Loops are an essential programming construct in JavaScript (and many other programming languages) because they allow you to repeat a block of code multiple times. Loops are useful when you want to perform a particular action or execute a set of instructions repeatedly, without having to write the same code over and over again.

Here are a few reasons why we use loops in JavaScript:

  1. Iteration: Loops enable iteration, which means executing a block of code repeatedly until a certain condition is met. For example, you can use a loop to iterate through an array and perform an operation on each element.

  2. Efficiency: Loops help optimize your code by reducing redundancy. Instead of duplicating the same code multiple times, you can encapsulate it within a loop and execute it as many times as needed.

  3. Automation: Loops allow you to automate repetitive tasks. For instance, if you have a list of items that need processing, you can use a loop to go through each item and apply the necessary operations.

  4. Dynamic behavior: Loops provide a way to handle variable or changing conditions. By using conditional statements within loops, you can control when to start or stop the loop based on specific criteria.

JavaScript provides several types of loops, including the for loop, while loop, do-while loop, and the for...in and for...of loops for iterating over objects and arrays.

Here's an example of a for loop in JavaScript that iterates over an array:

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

for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}

In this example, the loop starts with an initial value of i = 0 and continues until i is no longer less than the length of the numbers array. With each iteration, the loop prints the value of the corresponding array element.

Overall, loops provide a powerful mechanism for controlling the flow of execution in JavaScript and are essential for implementing repetitive tasks and iterating over collections of data.

The for loop

The for loop is one of the most commonly used loops in JavaScript. It allows you to repeat a block of code a specific number of times, typically based on a counter variable. The for loop consists of three parts: initialization, condition, and increment/decrement.

Here's the basic syntax of a for loop in JavaScript:

for (initialization; condition; increment/decrement) {
  // Code to be executed in each iteration
}

Let's break down each part of the for loop:

  1. Initialization: This part is used to initialize the loop counter or any other variables required for the loop. It typically executes only once before the loop starts. For example, you can declare and initialize a counter variable like let i = 0;.

  2. Condition: The condition is checked before each iteration. If the condition evaluates to true, the loop continues executing the code block. If the condition evaluates to false, the loop terminates, and the program continues with the next statement after the loop. For example, you can use a condition like i < 5 to continue the loop as long as i is less than 5.

  3. Increment/Decrement: This part is executed at the end of each iteration. It is used to modify the counter variable or any other variables involved in the loop. It allows you to control the flow of the loop and ensure that the condition eventually becomes false to terminate the loop. For example, you can increment the counter variable like i++ to move to the next iteration.

Here's an example that demonstrates a for loop that prints the numbers 0 to 4:

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

In this example, the loop initializes i to 0, checks if i is less than 5, and executes the code block (console.log(i)). After each iteration, i is incremented by 1 (i++). The loop continues until i is no longer less than 5, printing the values 0, 1, 2, 3, and 4.

You can use the for loop for a wide range of scenarios, such as iterating over arrays, performing calculations, generating sequences, or repeating a specific task for a known number of times. The flexibility and control offered by the for loop make it a powerful construct in JavaScript programming.

For-in loop

The for...in loop, which is used for iterating over object properties, not arrays. The for...in loop is specifically designed for iterating over the enumerable properties of an object.

Here's the correct syntax for the for...in loop in JavaScript:

for (variable in object) {
  // Code to be executed in each iteration
}

In each iteration of the for...in loop, the variable represents a different property name of the object being iterated.

Here's an example that demonstrates how to use the for...in loop to iterate over the properties of an object:

let obj = {
  Arpan: 90,
  Mrwhite: 45,
  Heisenberg: 56,
  Batman: 57,
  Bruce: 23
}

// For in loop
for (let a in obj) {
  console.log("Marks of " + a + " are " + obj[a])
}

In this example, the for...in loop iterates over each property of the object.

The output of the above code will be:

Marks of Arpan are 90
Marks of Mrwhite are 45
Marks of Heisenberg are 56
Marks of Batman are 57
Marks of Bruce are 23

For-of loops

The for...of loop is another iteration construct in JavaScript that is specifically designed for iterating over elements of iterable objects, such as arrays, strings, maps, sets, and more. It provides a simpler and more concise syntax compared to the traditional for loop when you only need to iterate over the values of an iterable.

Here's the basic syntax of a for...of loop in JavaScript:

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

In each iteration of the for...of loop, the variable represents a different value of the iterable object.

Let's look at an example of using the for...of loop to iterate over an array:

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

for (let num of numbers) {
  console.log(num);
}

In this example, the for...of loop iterates over each element of the numbers array. In each iteration, the num variable represents a different value from the array. The code block inside the loop simply logs the value to the console.

The output of the above code will be:

1
2
3
4
5

The for...of loop automatically handles iterating over the elements of the iterable object until there are no more elements left. It provides a simpler and cleaner syntax compared to the for loop when you only need to iterate over values and don't require the index or need to modify the iterable.

It's important to note that the for...of loop works with iterable objects, which are objects that implement the iterable protocol. Most built-in JavaScript data structures, such as arrays and strings, are iterable by default. Additionally, you can create your own iterable objects by implementing the iterable protocol.

Here's an example of using the for...of loop to iterate over a string:

for (let b of "Arpan") {
  console.log(b)
}

The output of the above code will be:

A
r
p
a
n

In this case, the for...of loop iterates over each character of the string and logs them individually.

The for...of loop offers a convenient way to iterate over the values of iterable objects, reducing the need for manual index tracking and providing a cleaner syntax for such scenarios.

Did you find this article valuable?

Support Arpan Mukherjee's Blogs by becoming a sponsor. Any amount is appreciated!