Ticker

6/recent/ticker-posts

For Loop in JavaScript

For Loop in JavaScript

1. Introduction The for loop is a control flow statement in JavaScript that allows you to repeatedly execute a block of code based on a specified condition. It is commonly used when you know the number of iterations required in advance.

2. Syntax The syntax for a for loop in JavaScript is as follows:

javascript
for (initialization; condition; iteration) { // Code to be executed in each iteration }
  • Initialization: It is an expression that initializes the loop counter. It is executed before the loop starts.
  • Condition: It defines the condition for the loop to continue iterating. If the condition evaluates to true, the loop continues; otherwise, it exits.
  • Iteration: It specifies the action to be performed after each iteration. It is executed at the end of each iteration.

3. Example Let's consider an example where we want to print the numbers from 1 to 5 using a for loop:

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

4. Explanation

  • The for loop begins by initializing i with a value of 1 (let i = 1).
  • The condition i <= 5 is evaluated. If it is true, the loop body is executed; otherwise, the loop is terminated.
  • In each iteration, the code inside the loop body (in this case, console.log(i)) is executed.
  • After executing the loop body, the iteration statement i++ increments the value of i by 1.
  • The loop continues until the condition i <= 5 becomes false.

5. Break and Continue Statements Inside a for loop, you can use the break statement to exit the loop prematurely and the continue statement to skip the current iteration and proceed to the next one.

  • The break statement can be used to terminate the loop entirely:
javascript
for (let i = 1; i <= 5; i++) { if (i === 3) { break; } console.log(i); }
  • The continue statement can be used to skip a specific iteration:
javascript
for (let i = 1; i <= 5; i++) { if (i === 3) { continue; } console.log(i); }

6. Conclusion The for loop is a fundamental construct in JavaScript that allows you to iterate over a sequence of values. It provides a compact and structured way to perform repetitive tasks. By understanding its syntax and usage, you can leverage the power of loops to efficiently handle various scenarios in your JavaScript programs.

Post a Comment

0 Comments