Tuesday, March 18, 2014

JavaScript for...in loop

There is one more loop supported by JavaScript. It is called for...in loop. This loop is used to loop through an object's properties.
Because we have not discussed Objects yet, so you may not feel comfortable with this loop. But once you will have understanding on JavaScript objects then you will find this loop very useful.

Syntax:

for (variablename in object){
  statement or block to execute
}
In each iteration one property from object is assigned to variablename and this loop continues till all the properties of the object are exhausted.

Example:

Here is the following example that prints out the properties of a Web browser's Navigator object:
<script type="text/javascript">
<!--
var aProperty;
document.write("Navigator Object Properties<br /> ");
for (aProperty in navigator)
{
  document.write(aProperty);
  document.write("<br />");
}
document.write("Exiting from the loop!");
//-->
</script>
This will produce following result:
Navigator Object Properties
appCodeName
appName
appMinorVersion
cpuClass
platform
plugins
opsProfile
userProfile
systemLanguage
userLanguage
appVersion
userAgent
onLine
cookieEnabled
mimeTypes
Exiting from the loop! 

No comments:

Post a Comment