JavaScript For-in Loop
JavaScript For-in Loop is used to loop through the items of an iterable object.
In this tutorial, we will learn how to define/write a JavaScript For-of loop, and its usage using example programs.
Syntax
The syntax of JavaScript For-of Loop is
for (item of iterableObj) {
//statements
}
where item is loaded with the next item of iterableObj object during each iteration.
for
and of
are keywords.
Examples
In the following example, we take an array, which is an iterable object, and use For-of loop to iterate over the items of this array.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var obj = ['apple', 'banana', 'orange'];
var output = document.getElementById('output');
for (item of obj) {
output.innerHTML += item + '\n';
}
</script>
</body>
</html>
Now, let us take a string object, and iterate over the character using For-of loop. String is an iterable object which returns next character during each iteration.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var obj = 'apple';
var output = document.getElementById('output');
for (item of obj) {
output.innerHTML += item + '\n';
}
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned about For-of Loop, its syntax, and usage with examples.