xxxxxxxxxx
forin Loop => iterates over the index in the array.
forof Loop => iterates over the object of objects.
xxxxxxxxxx
let list = [4, 5, 6];
for (let i in list) {
console.log(i); // "0", "1", "2",
}
for (let i of list) {
console.log(i); // "4", "5", "6"
}
// EXAMPLE 2
let pets = new Set(["Cat", "Dog", "Hamster"]);
pets["species"] = "mammals";
for (let pet in pets) {
console.log(pet); // "species"
}
for (let pet of pets) {
console.log(pet); // "Cat", "Dog", "Hamster"
}
xxxxxxxxxx
// for of
// used for arrays and strings
const array1 = ['a', 'b', 'c'];
for (const element of array1) {
console.log(element);
}
// Expected output: "a"
// Expected output: "b"
// Expected output: "c"
// for in
// used for objects
const object = { a: 1, b: 2, c: 3 };
for (const property in object) {
console.log(`${property}: ${object[property]}`);
}
// Expected output:
// "a: 1"
// "b: 2"
// "c: 3"
xxxxxxxxxx
/**
* for in loops over enumerable property names of an object.
* for of (new in ES6) does use an object-specific iterator and
* loops over the values generated by that.
**/
const arr = [3, 5, 7];
for (const i in arr) {
console.log(i); // logs "0", "1", "2", "foo"
}
for (const i of arr) {
console.log(i); // logs "3", "5", "7"
}
xxxxxxxxxx
for in loops over enumerable property names of an object.
for of (new in ES6) does use an object-specific iterator and loops over the values generated by that.