JavaScript For Loop.pdf_20250521_231246_0000
JavaScript For Loop.pdf_20250521_231246_0000
JavaScript - For
Loop
The JavaScript for loop is used to execute a block of code repeteatedly, until a
specified condition evaluates to false. It can be used for iteration if the number of
iteration is fixed and known.
The JavaScript loops are used to execute the particular block of code repeatedly. The 'for'
loop is the
most compact form of looping. It includes the following three important parts
Initialization − The loop initialization expression is where we initialize our counter
to a starting value. The initialization statement is executed before the loop begins.
Condition − The condition expression which will test if a given condition is true
or not. If the
condition
the controlis true, then the code given inside the loop will be executed. Otherwise,
Flow
Chart
The flow chart of a for loop in JavaScript would be as
follows −
Page 2 of
9
Adver
tisement -
Syntax
The syntax of for loop is JavaScript is as
follows −
Examples
Try the following examples to learn how a for loop works in
JavaScript.
Open
Compiler
<html
>
<head
<title> JavaScript - for loop </title>
>
</
head>
<body
<p id = "output"> </p>
> <script>
const output = document.getElementById("output");
output.innerHTML = "Starting Loop <br>"; let count;
for (let count = 0; count < 10; count++) {
Current Count : 8
Current Count : 9
Loop stopped!
Whenever you need to use the looping variable, even after the execution of the loop is
completed, you
can initialize a variable in the parent scope of the loop, as we have done in the below
code. We also
<html
>
<head
<title> Initialization is optional in for loop </title>
>
</
head>
<body
<p id = "output"> </p>
> <script>
let output = document.getElementById("output");
var p = 0; for (; p < 5; p++) {
Open
Compiler
<html
>
<head
<title> Conditional statement is optional in for loop </title>
>
</
head>
<body
<p id = "output"> </p>
> <script>
let output = document.getElementById("output");
let arr = [10, 3, 76, 23, 890, 123, 54] var p = 0; for
(; ; p++) {
if (p >= arr.length) {
break;
} o u t p u t . i n n e r H T M L + =
" a r r [ " + p + " ] - > " +
<br/>"; a r r [ p ] + "
}
< / s c
</ r i p t
body> >
</html
>
Outp
ut
arr[0] -> 10
arr[1] -> 3
arr[2] -> 76
arr[3] -> 23
arr[4] -> 890
Page 6 of
9
Open
Compiler
<html
>
<head
<title> Iteration statement is optional </title>
>
</
head>
<body
<p id = "output"> </p>
> <script>
let output = document.getElementById("output");
let str = "Tutorialspoint"; var p = 0; for (; ;) {
if (p >= str.length) {
break;
} o u t p u t . i n n e r H T M L + =
" s t r [ " + p + " ] - > " +
<br/>"; s t r [ p ] + "
p+
} +;
< / s c
</ r i p t
body> >
</html
>
Outp
ut
str[0] -> T
str[1] -> u
str[2] -> t
str[3] -> o
str[4] -> r
str[5] -> i
str[6] -> a
Page 7 of
9
str[7] -> l
str[8] -> s
str[9] -> p
str[10] -> o
str[11] -> i
str[12] -> n
str[13] -> t