What is a for/in loop?


#1

for(var hey in obj) {
console.log(hey);
}

I have this for loop but I do not know or understand what the IN part of the loop does.


#2

It's a common way to loop through an object.

Have a look at this article and play round with the example they have: https://www.w3schools.com/jsref/jsref_forin.asp


#3

`
// given an object,

var obj = { a: 1, b: 2, c: 3, d: 4 }
for (var key in obj) {
console.log(key);
}

// will output

a
b
c
d

for (var key in obj) {
console.log(obj[key]);
}

// will output

1
2
3
4

In our object, key is the keys, obj[key] is the values associated with each key.

The in operator targets each member of the object (property) by the list of key names, in any order.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.