The for-in loop is a special type of a loop that iterates over the properties of an object, or the elements of an array.
Every object has different properties and their values stored inside it.
In every iteration each property from object is assigned to a specified variable name and thae value becomes the value of the variable, then we can use the variable inside the loop. This loop continues till all the properties of the object are exhausted.
The block of code inside the loop will be executed once for each property.
Syntax
for (variablename in object) { // code to be executed }
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript For in Loop Statement </title>
</head>
<body>
<p>Click blow to see the properties of an object.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var person = {fname:"John", lname:"Snow", age:25};
var text = "";
var x;
for (x in person) {
text += person[x] + " ";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript For in Loop Statement </title>
</head>
<body>
<p> JavaScript Iterate Over an Array Using For in Loop</p>
<body>
<script>
// An object with some properties
var person = {"Name": "Shubham", "Surname": "Kandari", "Age": "26"};
// Loop through all the properties in the object
for(var prop in person) {
document.write("<p>" + prop + " = " + person[prop] + "</p>");
}
</script>
</body>
</html>