for
Loopfor
Loopfor
loopfor
loop examples
for
loop without the initialization part examplefor
LoopThe JavaScript for
loop is also known as an entry control loop. The JavaScript for
is test specified condition before executing a block of code. If the condition met true, then block of code will be executed.
Note:- It’s the concise form of loop.
for
Loopfor (initialization; condition; post-expression) {
// statements
}
The initialization
expression initializes the loop. The initialization expression is executed only once when the loop starts.
The condition
is check once before every iteration. The block of code
inside the loop is executed only when the condition
is met true
. If the condition
metfalse
. The execution of loop will be stopped.
The for
loop statement also evaluates the post-expression
after each loop iteration. Generally, update post-expression
(increment/decrement).
for
loopfor
loop examplesLet’s take some examples of using the for
loop.
The following example uses the javascript for
loop statement that print the numbers from 1 to 5.
<script>
for (var count = 1; count <= 5; count++)
{
document.write(count + "<br>")
}
</script>
The output of the script shown below:
1
2
3
4
5
How it works:
count
and initialize it to 1.count
.count
by 1 in each iteration of the loop.for
loop without the initialization part exampleThe following example uses a for
loop that omits the initialization part:
<script>
var j = 1;
for (; j < 10; j += 2)
{
document.write(j + "<br>")
}
</script>
The output of the script shown below:
1
3
5
7
9
The following example uses the javascript for
loop statement that sum of 1 to n the numbers.
<script>
let sum = 0;
let n = 5;
for(let i = 1; i <= n; i++)
{
sum = sum + i;
}
document.write("Sum of 1 to n number is " + sum+ "<br>")
</script>
The output of the script shown below:
Sum of 1 to n number is 15
How it works:
sum and n
and initialize.count
by 1 in each iteration of the loop.sum
variable.The following example uses the javascript program to find sum of n numbers:
<script>
let sum = 0;
let n = 5;
for(let i = 1; i <= n; i++)
{
sum = sum + i;
}
avg = sum/n;
document.write("Average of 1 to n number is " + avg + "<br>")
</script>
The output of the script shown below:
Average of 1 to n number is 3
How it works:
sum and n
and initialize.count
by 1 in each iteration of the loop.avg
variable.In this tutorial, you have learned what is for loop and how to use the JavaScript for
loop statements with various examples.
☞ Learn Vue.js from scratch 2018
☞ Learn JavaScript - Become a Zero to Hero
☞ JavaScript Programming Tutorial Full Course for Beginners
☞ Vue js Tutorial Zero to Hero || Brief Overview about Vue.js || Learn VueJS 2023 || JS Framework