📜  for loop -2 js - Javascript (1)

📅  最后修改于: 2023-12-03 15:00:49.954000             🧑  作者: Mango

For Loop in JavaScript

A for loop is a control flow statement that repeats a block of code a specified number of times. It consists of three parts: initialization, condition, and increment.

for (initialization; condition; increment) {
  // code to be executed
}
  • The initialization statement is executed one time at the beginning of the loop.
  • The condition statement is evaluated at the beginning of each iteration. If true, the loop continues. If false, the loop ends.
  • The increment statement is executed at the end of each iteration.
Example

Suppose we want to print the numbers 1 to 5 using a for loop.

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

Output:

1
2
3
4
5

In this example:

  • The initialization statement sets the variable i to 1.
  • The condition statement checks whether i is less than or equal to 5.
  • The increment statement increases i by 1 after each iteration.
Nested Loops

We can also use nested loops, which are loops within loops. Here is an example of a nested for loop that prints a multiplication table:

for (let i = 1; i <= 10; i++) {
  for (let j = 1; j <= 10; j++) {
    console.log(`${i} x ${j} = ${i * j}`);
  }
}

Output:

1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
...
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100

In this example, we have two for loops:

  • The outer loop iterates from 1 to 10.
  • The inner loop iterates from 1 to 10 for each value of the outer loop.
Conclusion

The for loop is a powerful construct in JavaScript that allows us to perform repetitive tasks with ease. By knowing how to use it, we can make our code more efficient and concise.