JavaScript for loop

Loops can run a block of code several times. As a result, loops come in handy if you want to run the same code multiple times, each time with a different value. In addition, the iteration usually runs a fixed number of times.

In JavaScript, loops are used to conduct repeated activities based on a condition. When conditions are analyzed, they typically return true or false. A loop will continue to run until the specified condition is false.

Example,

const fruits = ["Apples", "Oranges", "Mangoes", "Bananas", "Pineapple", "water melon"];

text += fruits [0] + "<br>";
text += fruits [1] + "<br>";
text += fruits [2] + "<br>";
text += fruits [3] + "<br>";
text += fruits [4] + "<br>";
text += fruits [5] + "<br>";

A better way to run this using a for loop in JavaScript is as follows.

let text2 = "";
for (let i = 0; i < fruits.length; i++) { text2 += fruits[i] + "
";
}
console.log(text2);
use a for loop to concatenate array elements
uses a for loop to concatenate array elements

The Syntax of the For Loop

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

initialization

Statement 1 is the initialization. It is the startup of the loop when we set our counter to a starting value. Before the loop starts, the initialization statement is executed.

Condition

Statement 2 is the condition. Now, the test statement determines whether or not a particular condition is true. If the condition evaluates to true, the script inside the loop will be executed; if it is false, the control will exit the loop.

Post-expression

The third statement is post-expression. Here, you can increase or reduce your counter with the iteration statement.

The above code denotes the syntax for the For Loop in JavaScript. We will now examine what each of the sections means.

  • Before the execution of the main block of code, statement 1 is executed one time.
  • The condition for execution of the block of code is determined by statement 2.
  • After executing the block of code, statement 3 is executed every time.
for (let j = 0; j < 10; j++) {
main_text += "count is " + j + "\n";
}
console.log(main_text)

According to the given example above:-

The first statement initializes a variable before the execution of the loop using the syntax,

let j = 0


The second statement is the definition of the condition for the loop to start running with the following syntax,

j < 10

On the other hand, the third statement increases the value of j (j++) with every code block execution in the loop.

About the first statement

Having the first statement is usually optional in most cases initializing the variable used in the for loop like the case in the above example (let j = 0). In addition, you are free to initialize as many values as you possibly can in the first statement, like in the following demo.

const fruits = ["Apples", "Oranges", "Mangoes", "Bananas", "Pineapple", "water melon"];
let i, len, textVal;

for (let j = 0, len = fruits.length, textVal = ""; j < len; j++) {
textVal += fruits[j] + "\n";
console.log(fruits[j])
}


initialize many values in the first statement
initialize many values in the first statement

Alternatively, you can avoid using the first statement on the off chance that the values are initialized before starting the loop.

let j = 2;
let len_val = fruits.length;
let text_val = "";
for (; j < len_val; j++) {
text_val += fruits[j] + "\n";
console.log(text_val)
}

It is not always the case for the second statement to evaluate the condition of the initial variable though it does so often. If you choose to omit statement 2, ensure a break inside the loop. However, if you ignore it by any chance, then the loop will never terminate. As a result, the browser will crash.

The usual term of operation is that the second statement will return false, causing the loop to end. But if the second statement returns true, the loop will start again.

The third statement is optional, though the core purpose remains to increase the variable. However, it also decrements (–) or increments (++) the initial variable.

const fruits = ["Apples", "Oranges", "Mangoes", "Bananas", "Pineapple", "water melon"];

let j = 0;
let len_val = fruits.length;
let text_val = "";

for (; j < len_val; ) { 
  text_val += fruits[j] + "";
j++;
}
use for loop to count array elements
use for loop to count array elements

Infinite For Loop in JavaScript

A for loop runs indefinitely if the test condition is true until the memory is full. An example of an Infinite instance in For Loop in JavaScript is as follows,

// Defining an infinite for loop
let j = 1;
for(j; j > 0; j++) {
console.log(j)
}
infinite loop
infinite loop

The condition in the preceding program is always true, causing the code to execute indefinitely.

Example of a for loop without a loop body

Surprisingly, the for statement can also include an empty sentence. It would help if you used a semicolon (;) after the ‘for’ statement in this situation. In the following example, the total numbers from 1 to 5 are calculated.

sum_val = 0;
for (let j = 0; j <= 5; j++, sum_val += j);
console.log(sum_val);

Because the expression is near the end of the loop, it utilizes an empty statement in the body.

Example of a for loop with no expression

Because all three expressions in the for loop statements are optional, you can leave them out entirely. To end the loop, you must use a break statement and change the counter variable to make the condition for the break statement true at some point.

// initialize x variable
let x = 1;
for (;;) {
// terminate the loop if x is greater than 20;
if (x > 20) break;
console.log(x);
// increase the counter x
x += 2;
}
for loop with no expression
for loop with no expression

Example of a for loop without a condition

The condition expression, like the initialization expression, is optional. If the condition expression is omitted, the loop must be terminated with a break statement.

for (let x = 1;; x += 2) {
console.log(x);
if (x > 20) {
break;
}
}
for loop without a condition
for loop without a condition

Example 1: Show the Sum of a given count of Natural Numbers

// program to show the sum of a given number of natural numbers

let sum_val = 0;
const num_vals = 50

// looping from j = 1 to num_vals
// in each iteration, j is increased by 1
for (let j = 1; j <= num_vals; j++) {
sum_val += j; // sum_val = sum_val + i
}

console.log('The sum of '+n +' is : ', sum_val);
Show the Sum of a given count of Natural Numbers
Show the Sum of a given count of Natural Numbers

In the example above, sum_val is first initialized to 0 with a for loop iterating from a jth value of 1 to 50. During each iteration, the sum_val is increased by the value of j, then the value of j is increased by 1.

The loop will terminate when the test condition becomes false, which in our case is 51. Thus, the sum will be equal to the cumulative sum_val.

The other way to rewrite the above program is as follows.

// program to show the sum of a given count of natural numbers
let sum_val = 0;
const num_vals = 50;

// looping from j = sum_val to 1
// in each iteration, j is decreased by 1
for(let j = num_vals; j >= 1; j-- ) {
// adding i to sum in each iteration
sum_val += j; // sum_val = sum_val + j
}


console.log('sum values is :',sum_val );
simplified code to show the sum of a given count of natural numbers
simplified code to show the sum of a given count of natural numbers

This program generates the same results as the previous example. Programming is all about logic. Therefore you may perform the same objective in a variety of ways. Even though both approaches are correct, you should strive to make your code easily readable and more understandable. The latter is highly critical, especially when working on production code that someone else can later maintain.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *