3 Example(s) of JavaScript for in statement


Description :

JavaScript for-in loop is used to iterate over the properties of an object. See the code snippet:


JavaScript for in statement Example - 1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>  
 <body>
 <p id="sample"></p>

<script>
var txt = "";
var person = {fname:"Vishal", lname:"Garg", age:29}; 
var col;
for (col in person) {
    txt += person[col] + " ";
}
document.getElementById("sample").innerHTML = txt;
</script>
</body>
</html>

Output

Description :

Example of for-in:


JavaScript for in statement Example - 2
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>  
 <body>
 <p id="sample"></p>

<script>
var txt = "";
var obj = {a:1, b:2, c:3};
    
for (var prop in obj) {
  txt+=obj[prop] + " ";
}
document.getElementById("sample").innerHTML = txt;
</script>
</body>
</html>

Output

Description :

Example of JavaScript for-in :


JavaScript for in statement Example - 3
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>  
 <body>
 <p id="sample"></p>

<script>
    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>
</body>
</html>

Output