Javascript – for – for/in

Loops can execute a block of code a number of times.

<!DOCTYPE html>
<html>
<body>

<script>

for (var x=0;x<10;x++)
{
document.write(x + "<br>");
}
</script>

</body>
</html>

The result is:
0
1
2
3
4
5
6
7
8
9

This Statement executes 10 times:

document.write(x + "<br>");

1) The initial value is -> var x=0
2) It adds 1 unit -> x++
3) It checks -> x<10 -> if true -> It writes x
4) It checks -> x<10 -> if false -> It does not write x

Syntax:

for (statement 1; statement 2; statement 3)
  {
  the code block to be executed
  }

Statement 1 is executed before the loop (the code block) starts.
Statement 2 defines the condition for running the loop (the code block).
NOTICE: If you omit statement 2, you must provide a break inside the loop
Statement 3 is executed each time after the loop (the code block) has been executed.

To read Array contents:

<!DOCTYPE html>
<html>
<body>

<script>
cars=["BMW","Volvo","Saab","Ford"];
for (var i=0;i<cars.length;i++) // - cars.lenght - is the number of element in the array
{
document.write(cars[i] + "<br>"); // 1=0 is BMW
}
</script>

</body>
</html>

To read Object contents: for/in

<!DOCTYPE html>
<html>
<body>
<p>Click the button to loop through the properties of an object named "person".</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script>
function myFunction()
{
var x;
var txt="";
var person={fname:"John",lname:"Doe",age:25}; 

for (x in person)
{
txt=txt + person[x];
}

document.getElementById("demo").innerHTML=txt;
}
</script>
</body>
</html>

My official WebSite >