JavaScript JS Tutorial JS Objects JS Functions JS Classes JS Async JS HTML DOM JS Browser BOM JS Web APIs JS AJAX JS JSON JS vs jQuery JS Graphics



JS Loop For

JavaScript is a popular programming language used for creating interactive web pages. One of the most important features of JavaScript is its ability to loop through a set of data or code multiple times. The for loop is one of the most commonly used loops in JavaScript, and it allows developers to execute a block of code repeatedly based on a specified condition.

Brief Explanation of JS Loop For

The for loop in JavaScript is used to iterate over a set of data or code a specific number of times. It consists of three parts: the initialization, the condition, and the increment. The initialization is executed only once at the beginning of the loop and is used to set the initial value of the loop counter. The condition is evaluated at the beginning of each iteration and determines whether the loop should continue or not. The increment is executed at the end of each iteration and is used to update the loop counter.

The syntax for the for loop in JavaScript is as follows:

for (initialization; condition; increment) {
  // code to be executed
}

Let's take a look at some examples of how the for loop can be used in JavaScript.

Code Examples

Example 1: Print the numbers from 1 to 10

for (let i = 1; i <= 10; i++) {
  console.log(i);
}

This code initializes the variable i to 1, sets the condition to continue looping as long as i is less than or equal to 10, and increments i by 1 at the end of each iteration. The console.log() function is used to print the value of i to the console.

Example 2: Print the even numbers from 1 to 10

for (let i = 1; i <= 10; i++) {
  if (i % 2 === 0) {
    console.log(i);
  }
}

This code initializes the variable i to 1, sets the condition to continue looping as long as i is less than or equal to 10, and increments i by 1 at the end of each iteration. The if statement checks whether i is even (i.e., whether it is divisible by 2 with no remainder) and prints the value of i to the console if it is.

Example 3: Calculate the sum of the numbers from 1 to 10

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

This code initializes the variable sum to 0, initializes the variable i to 1, sets the condition to continue looping as long as i is less than or equal to 10, and increments i by 1 at the end of each iteration. The sum += i statement adds the value of i to the sum variable at each iteration. Finally, the console.log() function is used to print the value of sum to the console.

Conclusion

The for loop is a powerful tool in JavaScript that allows developers to iterate over a set of data or code multiple times. By understanding the syntax and examples of the for loop, developers can create more efficient and effective JavaScript code.

References

Activity