JavaScript For Loop

Loops - For Loop

Loops :

In JavaScript code, we may have to repeat specific action some number of times.

For example, consider a variable counter which has to be incremented 5 times.

One way of doing it is, writing increment statement 5 times as shown below:

JS Loops

Looping statements in JavaScript helps to execute statement(s) required number of times without repeating code.

JavaScript supports popular looping statements:

javascript types of loops

Let us understand each of them in detail.

'for' loop is used when the block of code is expected to execute for a specific number of times. To implement it, use the following syntax.

JS For loop syntax

Below example shows incrementing variable counter 5 times using for loop:

Also, shown below is output for every iteration of the loop.

JS For loop example
JS For loop example 2

Demo :

      div#maincontent {
          height: 200px;
          width: 500px;
          border: 1px solid #cee2fa;
          text-align: left;
          color: #08438e;
          font-family: calibri;
          font-size: 20;
          padding: 5px;
      div#heading {
          text-decoration: bold;
          text-align: center;
          margin-top: 80px;
          width: 500px;
          border: 1px solid #cee2fa;
          text-align: center;
          color: #08438e;
          background-color: #cee2fa;
          font-family: calibri;
          font-size: 20;
          padding: 5px;
      h2 {
          padding: 0;
          margin: 0;
      <div id="heading">
        <h2>Booking Summary</h2>
      <div id="maincontent">
            var seats = 3;
            var costPerTicket = 320;
            var discount = 10;
            var total = seats * costPerTicket;
            const percent = 100;
            var discountedCost;
            totalCost = 0;
              "Actual cost per ticket: Rs." + costPerTicket + "<br><br>"
            //Requirement 2 b: Calculating discount based on the sequence of customers booking the ticket
            for (index = 1; index <= seats; index++) {
              discountedCost =
                costPerTicket - (discount / percent) * costPerTicket;
              document.write(discount + " % off on ticket " + index + "<br>");
              totalCost = totalCost + discountedCost;
              discount = discount + 2;
              "<br>" + "Actual amount for " + seats + " tickets: Rs." + total
            document.write("<br>" + "Amount payable: Rs." + totalCost);
#javascript_for_loop #For_Loop_in_javascript #js_for_loop #node_js_for_loop #for_in_loop_in_javascript #javascript_for_loop_example #javascript_for_of_loop

(New page will open, for Comment)

Not yet commented...