For…In Statement : Loop Through the properties of an object in JavaScript

February 1, 2025 No Comments » Hits : 400





For…In Statement : Loop Through the properties of an object

  1. The for…in statement loops through the properties of an object.
  2. The code in the body of the for…in loop is executed once for each property.

Live Example : For..In Statement

<html>
<body>
<script type="text/javascript">
var book = {
             bname  : "Java Programming",
             author : "Pritesh Taral",
             pages  : 275
             };
var x;
for (x in book)
{
document.write(book[x] + "");
}
</script>
</body>
</html>

Output :

Java Programming Pritesh Taral 275

Explanation :

  1. We have declared object book having 3 properties.
  2. Properties are - bname,author and pages.
  3. x is declared as index variable which is used while iterating through object properties.
  4. For..In Loop will print values of all properties in a sequence in which they are declared.

Incoming search terms: