Introduction
In the previous chapter, we learned about Conditional Statements in JavaScript and how to use these statements with example programs.
In this chapter, we learn about looping and jump control statements. Loops can execute blocks of code for any number of times.
The following Looping statements are supported in JavaScript:
- For Loop
- While Loop
- Do while Loop
For Loop Statement
For a loop, when you execute a loop for a fixed number of times, the loop does three specified tasks (Statement 1, Statement 2, Statement 3). The following code shows the general Syntax of the 'for' statement.
Syntax
- for (initialization; condition; increment/ decrement)
- {
- Executed these statements;
- }
Example
- <!DOCTYPE html>
- <html>
- <head>
- <title>For Loop Statement in JavaScript</title>
- </head>
- <body>
- <h2>For loop Statement in JavaScript</h2>
- <script type="text/javascript">
- var i;
- for(i=0;i<=10;i++)
- {
- document.write("The number is :" +i +"<br/>");
- }
- </script>
- </body>
- </html>
Output
While Loop Statement
The while statement is the simplest of all looping statements. The while loop repeats a block of code, as long as a specified condition is true. In the for loop, we have seen the three specific tasks performed. It is specified at the same place in the Statement, and the same three specific tasks are performed in the while loop also, but the while loop conditions and initialization are occurring in different places. The following code show general Syntax of the While statement:
Syntax
- while (condition)
- {
- Execute these statements;
- Increment/decrement;
- }
Example
- <!DOCTYPE html>
- <html>
- <head>
- <title>While Loop Statement in JavaScript</title>
- </head>
- <body>
- <h2>While loop Statement in JavaScript</h2>
- <script type="text/javascript">
- var i=0;
- while(i<=10)
- {
- document.write("The number is :" +i +"<br/>");
- i++;
- }
- </script>
- </body>
- </html>
Output
do-while Statement
The do-while statement is similar to the while statement. In the do-while statement, the condition is present at the outside of the statement. It will execute at least once even if the condition is to be not satisfied. If the condition is true, it will continue executing and once the condition becomes false, it stops the code execution. The following code shows general Syntax of the While statement:
Syntax
- do
- {
- Execute the statements;
- Increment/decrements;
- }
- while (condition)
Example
- <!DOCTYPE html>
- <html>
- <head>
- <title>Do While Loop Statement in JavaScript</title>
- </head>
- <body>
- <h2>Do While loop Statement in JavaScript</h2>
- <script type="text/javascript">
- var i=0;
- do
- {
- document.write("The number is :" +i +"<br/>");
- i++;
- }
- while(i<=10)
- </script>
- </body>
- </html>
Output
Summary
In this chapter, we learned about looping statements in JavaScript and how to use these statements in JavaScript with example programs.