Infolinks

Breaking

Adsense

Thursday, April 21, 2016

SIMPLE PROGRAM USING WHILE LOOP IN JAVASCRIPT

Hi there! This article is about creating a simple program that uses WHILE loop using javascript. Loops can execute a block of code as long as a specified condition is true. Loops are important to minimize codes that are executed for several times.

Let’s say you want to display numbers from 1 to 10, what will you do? Are you going to print those numbers manually from 1 to 10? But what if you are to display from 1 to 100? Are you still going to manually write those? It is possible, but it takes effort and time to achieve it. Unlike using a loop statement which will be 10-15 lines of codes if you are to display numbers from 1 to 10 and 100+ lines of codes if from 1 to 100. But if you are going to use a looping statement, you can achieve all of that in less than 10 lines of codes.

JAVASCRIPT WHILE LOOP SYNTAX


while (condition) {
        code to be executed
}

EXAMPLE JAVASCRIPT WHILE LOOP

In the following example, the code inside the curly braces {} will run over and over again as long as the condition inside the parenthesis is true. This code will display numbers from 1 to 10. The

JAVASCRIPT WHILE LOOP CODE


<html>
   <head>
      <script>
          var counter;
          counter=1;
          while(counter<=10)
              {
                   document.writeln(counter);
                   counter++;
              }
       </script>
    </head>
</html>
I will explain the code for you to understand well. Javascript codes are usually found inside the head tag of your html document. First thing to do is to declare all variables that you are going to use like declaring the variable counter. Next is, initialize the value of your counter which is 1 since the program will start from 1. While keyword is used to start a while loop in most programming language followed by the condition. We stated in our condition that if the counter is less than or equal to 10, the program will execute the code inside the curly braces. Don’t forget to increment your counter because your loop will never stop and your browser will crash.

SIMPLE PROGRAM USING WHILE LOOP IN JAVASCRIPT

No comments:

Post a Comment

Adbox