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).
let cars = {
carName: 'Sorento',
make: 'Kia',
year: 2016
}
let cars = {
carName: 'Sorento',
make: 'Kia',
year: 2016
}
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
vince
vince15mo ago
This may not directly answer your question but JS has a lot of ways to do 1 thing.
dellannie
dellannie15mo ago
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
13eck
13eck15mo ago
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 😜
dellannie
dellannie15mo ago
I just tried something with the object.keys and object.entries i rather the other options available
13eck
13eck15mo ago
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
Want results from more Discord servers?
Add your server