Q:

for of vs for in javascript

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"
}
3

 var person = {fname:"John", lname:"Doe", age:25}; 

var text = "";
var x;
for (x in person) {

    text += person[x] + " ";

 } 
3
void main() {
  List subjects = ['Math', 'Biology', 'Economic', 'History', 'Science'];
  for (String sName in subjects) {
    print(sName);
  }
}
0
const array = ['a', 'b', 'c', 'd'];

for (const index in array) {
	console.log(array[index])
}

// Result: a, b, c, d
0
for (variable in enumerable) {
	// do stuff
}
0
Object.prototype.objCustom = function () {}; 
Array.prototype.arrCustom = function () {};

let iterable = [3, 5, 7];
iterable.foo = "hello";

for (let i in iterable) {
  console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
}

for (let i of iterable) {
  console.log(i); // logs 3, 5, 7
}
0

New to Communities?

Join the community