For/Of Loop:
- It is called enhanced for loop
- It is used to iterate Array or Collection easily.
Note: Generally, we iterate an array by specifying their index values.
<html>
<body>
<script>
var arr = [10, 20, 30, 40, 50];
document.write("Array elements are : <br/>");
for (var i=0 ; i<arr.length ; i++){
document.write(arr[i] + "<br/>");
}
</script>
</body>
</html>
In case of For/Of loop, no need to specify the index to iterate the elements of Array or Collection:
<html>
<body>
<script>
var arr = [10, 20, 30, 40, 50];
document.write("Array elements are : <br/>");
for(var x of arr){
document.write(x + "<br/>");
}
</script>
</body>
</html>
We can iterate any type of array using for/of easily:
<html>
<body>
<script>
var arr=["HTML", "JavaScript", "CSS", "Angular", "VueJS"];
document.write("Array elements are : <br/>");
for(var s of arr){
document.write(s + "<br/>");
}
</script>
</body>
</html>
Limitations: For/of loop can process elements only in forward direction. For/of loop can process elements one by one
Display Array in Reverse Order: We must use for loop only
<html>
<body>
<script>
var arr = [10, 20, 30, 40, 50];
document.write("Array elements are : <br/>");
for(var i=arr.length-1 ; i>=0 ; i--){
document.write(arr[i] + "<br/>");
}
</script>
</body>
</html>
for/of loop: To process elements of Array/Collection only in forward direction.
Display even number in the given array using for-loop:
<html>
<body>
<script>
var arr = [5, 2, 9, 1, 6, 4, 7, 3];
document.write("Even elements : <br/>");
for(var i=0 ; i<arr.length ; i++){
if(arr[i]%2==0)
document.write(arr[i] + "<br/>");
}
</script>
</body>
</html>
The above program we can easily perform using for/of loop:
<html>
<body>
<script>
var arr = [5, 2, 9, 1, 6, 4, 7, 3];
document.write("Even elements : <br/>");
for(var x of arr){
if(x%2==0)1
document.write(x + "<br/>");
}
</script>
</body>
</html>