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.
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. TheJAVASCRIPT 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.
No comments:
Post a Comment