JavaScript While Loop

Loops - While Loop

while :

'while' loop is used when the block of code is to be executed as long as the specified condition is true. To implement the same, we use the following syntax:

JS while syntx

The value for the variable used in the test condition should be updated inside the loop only.

Below example shows incrementing variable counter 5 times using while loop.

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

JS While loop example

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
                index = 1;
                while (index <= seats) {
                    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_while_loop #While_Loop_in_javascript #javascript_do_while #javascript_while #do_while_loop_javascript #js_while_loop #js_do_while #looping_structures_in_javascript

(New page will open, for Comment)

Not yet commented...