(6) Explanation, how does the for/in loop work?


#1

Exercise 6: List 'em all!


I have a few questions about this exercise:

In this exercise, they show you the for/in loop. I have no idea how it's different from a regular for loop. That's my first question.

They also show you this:

for (var key in object) {
  // Use object[key] to access
  // the corresponding value
}

I know I could just copy and paste this code (filling in the console.log part), but I don't understand how this code works. And I know it will bite me later if I don't find out now. That's my second question.


So I want to know:

  1. What makes a for/in loop different from a regular for loop?
  2. What does the for/in loop that they showed mean? Especially the parameter (var key in object)

Thank you! :heart:


#2

A regular for loop usually repeats a certain amount of times, specified by a number (for (var i = 0; i < 8; i++;)) but a for/in loop does something for every item in an object. You could use this loop on an array, like so:

var myArray = ["Hello", "World"];
for (var item in myArray) {
    console.log(item);
}

This will print each word in the array to the console.


#3

from MDN:

The for...in statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.

the for in loop is a built in loop in javascript which loops over an object for you. You can't use a regular loop to access to items in objects (however how js works under the hood)

A normal loop would be:

test = ["one","two","three"]
for (var i = 0; i < test.length; i++){
  key = test[i];
}

here i use indexes to access the items of the array, but in a for in loop this is done for you, in each run of the loop key gets assigned a new property every time, everything is done for you


#4

Thank you, I think I understand!

And thank you, @toplearner. If I could, I'd mark both of your responses as the answer.


#5

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