JavaScript Loops #Part 6
What is a Loops in JavaScript ??
Looping refers to the ability of a block of code to repeat itself. This repetition can be for a predefined number of times or it can go until certain conditions are met.
Types of Loop in JavaScript
1. for Loop
2. while Loop
for Loop
The for Loop is the most basic type of loop and resembles a for loop in most other programming languages, including ANSI C.
Syntax
for(expression 1; conditions; condition 2)
{
// JavaScript commands
}
where, expression 1 sets up a counter variable and assign the initial value. The declaration of the counter variable can also be done here itself, condition specifics the final value for the loop to fire the loop fires till condition evaluate to true. Condition 2 specifies how the initial value in expression 1 is incremented.
Example
Print numbers from 10 to 1
<script>
for(var num=10; num>=1; num--)
{
document.writeln(num);
}
</script>
While Loop
The while Loop provide a similar functionality.
Syntax
while(condition)
{
//JavaScript commands
}
Where, the condition is a valid JavaScript expression that evaluate to a Boolean value. The JavaScript commands execute as long as the condition is true.
Example
Print numbers from 1 to 10
<script>
var num= 1;
while(num <= 10)
{
document.writeln(num);
num++;
}
</script>