Loops
while
while
A while loop repeatedly executes a code block as long as a specified condition is true. It is great for when we don't know how many times we need to do something, but must continue to do them until something happens to change the condition.
The parts of a while loop
for
for
A for loop is used for when we know exactly how many times we want to loop. This is very useful for repeating sections of code a certain number of times but is also very commonly used when accessing or manipulating elements in an array or similar collection.
The parts of a for loop
In other words, you declare a variable to be used as the iterator and test to see if that variable passes a condition in order to run the code block. The update statement runs after the code block is executed.
Very commonly, you will use it to loop through an array.
for...of
for...of
A for...of loop is a newer construct, similar to a for loop in other languages like Python. It is specifically used for iterating over an array but the code is easier to read and understand.
for...in
for...in
A for...in loop is similar to a for...of, but good for looping through all the key-value pairs in an Object.
Exercise
Implement Fizz Buzz. Loop from 1 to 100. If the number is divible by both 3 and 5, print "fizzbuzz". Otherwise, if the number if divisible by 3, print "fizz", or, if the number is divisible by 5, print "buzz". If none of the above are true, print the number. This is a very common interview question!
Split class in half. Group 1: use a for loop Group 2: use a while loop
Popcorn Class Exercise (one student per line of code)
Use a for...in
loop to examine the phoneBook
Object below and print out the names of all the people who share the phone number "333-333-3333".
Last updated