javascript for loop

Javascript For Loop 2020 Updated

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

Example: We have an array whose name is “language”. But we can take any name.
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. Because it helps time and reduce file size.

Syntax : 

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

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

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

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

Javascript For Loop 2019 Updated 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. Because it helps to improve.

More Related Post

Leave a comment

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