JavaScript For ... In Statement

previous next


The for ... in statement is used to loop (iterate) through the elements of an array or through the properties of an object.


JavaScript For ... In Statement

The for ... in statement is used to loop (iterate) through the elements of an array or through the properties of an object.

The code in the body of the for ... in loop is executed once for each element/property.

Syntax

for (variable in object)
{
  code to be executed
}

The variable argument can be a named variable, an array element, or a property of an object.

Example

Using for ... in to loop through an array:

<html>
<body>
<font face="Verdana" size=2>


<script type=
"text/javascript">
  var i
  var city = new Array()
  city[0] = "Rabat"
  city[1] = "Casablanca"
  city[2] = "Marrakech"
  city[3] = "Agadir"
  city[4] = "Khouribga"

  for (i in city)
  {
    document.write("The city "+ i + " is: " + city[i] + "<br>")
  }
</script>

</font>
</body>
</html>

Result

The city 0 is: Rabat
The city 1 is: Casablanca
The city 2 is: Marrakech
The city 3 is: Agadir
The city 4 is: Khouribga

 


Try it

To see how HTML and JavaScript work, you can only push the submit button, or you can make your own HTML and JavaScript code.

           

 


previous next