How to create and use loops (for, while) in JavaScript?

In JavaScript, you can use loops to repeat a block of code multiple times. There are two types of loops you can use: for loop and while loop. Here is how you can create and use them:

  1. for loop: The for loop is used when you know the number of iterations in advance.

    Syntax:

    for (initialization; condition; iteration) { // code to be repeated }
    • Initialization: Define a variable and its initial value.
    • Condition: The loop will continue as long as this condition is true.
    • Iteration: Increment or decrement the variable value after each iteration.

    Example:

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

    Output:

    0 1 2 3 4
  2. while loop: The while loop is used when the number of iterations is not known in advance.

    Syntax:

    while (condition) { // code to be repeated }
    • Condition: The loop will continue as long as this condition is true.

    Example:

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

    Output:

    0 1 2 3 4

In both loop types, you can manipulate the loop variable inside the loop body to control the program flow. Make sure to include a way to exit the loop to prevent infinite looping.