javascript for loop

Javascript For Loop

Javascript For Loop is used to iterate the block of statements. The Loop helps to run the same code again and again. Loop can be iterate with different values also. We explain For Loop with the help of Javascript Array.

Example: We have an array whose name is “Language”.
var language = [“PHP”, “Java”, “C”, “JavaScript”,”Ruby”];

To write all elements of the above array without using For Loop. We have to write like following.

document.getElementById("myParagraph").innerHTML = language[0];
document.getElementById("myParagraph").innerHTML = language[1];
document.getElementById("myParagraph").innerHTML = language[2];
document.getElementById("myParagraph").innerHTML = language[3];
document.getElementById("myParagraph").innerHTML = language[4];

Above method of writing each element of the array is not efficient. To use the best way, we need to use Javascript For Loop.

Syntax : 

for (statement 1; statement 2; statement 3) {
  // Statemets
}

Statement 1: First Statement is used to initialize the variable. It executes only one time before executing the statements.

Statement 2: In the Second Statement, we check the condition for executing the Statements.

Statement 3: It is used to  increment or decrements the value.

For Loop Example :

Example 1 :

<html>
<head>
<title>Developer Helps | Javascript Array</title>
</head>
<body>
<h2>JavaScript Array Using Literal</h2>
<p id="lang"></p>

<script>
var language = ["PHP", "Java", "C", "JavaScript","Ruby"];
var length = language.length;
for (i = 0 ; i < length ; i++) {
  document.getElementById("lang").innerHTML += language[i]+"<br>";
}
</script>

</body>
</html>

Output :

PHP
Java
C
JavaScript
Ruby

Example 2:

<html>
<head>
<title>Developer Helps | Javascript Array</title>
</head>
<body>
<h2>JavaScript Array Using Literal</h2>
<p id="lang"></p>

<script>
var language = ["PHP", "Java", "C", "JavaScript","Ruby"];
var length = language.length;
for (j in language) {
  document.getElementById("lang").innerHTML += language[j]+"<br>";
}
</script>

</body>
</html>

Output :

PHP
Java
C
JavaScript
Ruby

Thanks for the reading post. I hope you like and understand the post. If you have any doubt regarding this post please comment below.

More Related Post

Leave a comment

Your email address will not be published. Required fields are marked *

0 0 0
FOLLOW ON