JavaScript For-in Loop
JavaScript For-in Loop is used to loop through the properties of an object.
In this tutorial, we will learn how to define/write a JavaScript For-in loop, and its usage using example programs.
Syntax
The syntax of JavaScript For-in Loop is
for (key in object) {
//statements
}
where key of each property can be accessed during that loop run, using which we can get the corresponding value.
for
and in
are keywords.
Examples
In the following example, we take an object where the objects consists of some properties (key:value pairs), and iterate over these properties using For-in loop.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var obj = {name: 'Apple', age: '22', location: 'California'};
for (key in obj) {
let value = obj[key];
document.getElementById('output').innerHTML += key + '\t:\t' + value + '\n';
}
</script>
</body>
</html>
In the following example, we get the HTML element with the id t1254
and print all its key:value pairs to the pre block element.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<div id="t1254" class="c88"></div>
<pre id="output"></pre>
<script>
var obj = document.getElementById('t1254');
for (key in obj) {
let value = obj[key];
document.getElementById('output').innerHTML += key + '\t:\t' + value + '\n';
}
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned about For-in Loop, its syntax, and usage with examples.