JAVASCRIPT FOR IN LOOP
JavaScript for in loop is used to loop through properties of an object.
For In Loop Syntax:
for (key in object) { //can also be variable in array
// code
}
Usage on a sample JavaScript object
const car = { company: "Toyota", model: "Corolla", year: 2021 };
let text = "";
for (let x in car) {
text += car[x] + " ";
}
Live Demo!
In this example, the car object is iterated over in the for in loop. A key is returned in each iteration which is used to access the value of the key. The value of the key is car[x].
They for in loop can also be applied to arrays.
const cars = ["Corolla", "Bugatti", "Tesla"];
let text = "";
for (let x in cars) {
text += cars[x] + " ";
}
Live Demo!