Loops
When you have a collection of things, like an array or object, you can loop through its contents with a for…in
or for…of
loop.
toDoList = [
"Drop Robin off at school"
"Bring cape to drycleaner"
"Clean up cave"
"Deal with that Penguin person"
"Pick up Robin from school"
"Pick up cape from drycleaner"]
If you wanted to print each element in the list, you could manually type toDoList[0]
, toDoList[1]
, etc. to go through all the items in this list, but it’s easier to use a for…in
loop:
for item in toDoList
print "Meticulously and seriously doing ‘#{item}’… Done!"
» "Meticulously and seriously doing ‘Drop Robin off at school’… Done!"
» "Meticulously and seriously doing ‘Bring cape to drycleaner’… Done!"
» "Meticulously and seriously doing ‘Clean up cave’… Done!"
» "Meticulously and seriously doing ‘Deal with that Penguin person’… Done!"
» "Meticulously and seriously doing ‘Pick up Robin from school’… Done!"
» "Meticulously and seriously doing ‘Pick up cape from drycleaner’… Done!"
Note: I named my variable item
, but you can pick any word that makes sense; task
would have worked as well.
For looping through objects, we have for…of
. This kind of loop will return the key and the value of each property.
person =
name: "Selina Kyle"
secretIdentity: "Catwoman"
favoriteCocktail: "White Russian"
for key, value of person
print "This person’s #{key} is #{value}."
» "This person’s name is Selina Kyle."
» "This person’s secretIdentity is Catwoman."
» "This person’s favoriteCocktail is White Russian."
Again, I used key, value
, but you can use any two words.
When you use for…of
on an array, the first value (here: number
) will contain the item’s index number.
for number, value of todoList
print "Task nr. #{number} is: ‘#{value}’."
» "Task nr. 0 is: ‘Drop Robin of at school’."
» "Task nr. 1 is: ‘Bring cape to drycleaner’."
» "Task nr. 2 is: ‘Clean up cave’."
» "Task nr. 3 is: ‘Deal with that Penguin person’."
» "Task nr. 4 is: ‘Pick up Robin from school’."
» "Task nr. 5 is: ‘Pick up cape from drycleaner’."
Similarly, when using for…in
on an object, you’ll only get the values returned, and not the keys.
When to use loops
Since loops are handy for ‘doing the same thing to many things’ it often makes sense to save layers in an array just to be able to loop them. Whenever you find yourself making the same changes to different layers, or creating many similar layers, consider using a loop.