for, for of, for in loops
after finally starting to understand loops and how they work i havea curios question.
Lets say we have an object like the one listed below and we need to loop over this object(obviously these will be more complex in a real life situation).
If i can use for in or for of loop to loop through this object what would be the reason to use a regular for loop instead of the for of or for in?
I'm trying to to figure out just an idea on why one can be more important than the other
5 Replies
This may not directly answer your question but JS has a lot of ways to do 1 thing.
Thats what I was thinking honestly. I'm starting to notice this as I learn. In my little brain im here thinking why do this when I can do it this way and its cleaner
thats why I ask if there is some real or major reason behind it
There is little to no reason to use a traditional
for
loop to iterate an object as there is no direct way to access the object's keys or values via a for
loop.
for...of
loops are designed to iterate through an iterable (like arrays, sets, maps) which an object isn't. That leaves for...in
…which "…iterates over all enumerable string properties of an object" (MDN link).
TL; DR: iteration over an object should use a for...in
loop
Of course, you could use Object.entries(obj)
to get an array of arrays that consist of the [key, value]
of the object and use a for...of
from that colection…or Object.keys(obj)
to get an array of the object's keys. Or Object.values(obj)
to get an array of the values in the object and use a for...of
loop over that array 😜I just tried something with the object.keys and object.entries i rather the other options available
Object.keys() and a for...of is the same as a for...in with one more step :p
Unles you need the array to do something in addition to the for...of loop it's not really worth it, IMO