Day 8: Consolidation 2
Lesson 1: Loops
For
Let's print 5 numbers one after another:
1for (let loopCounter = 0; loopCounter < 5; loopCounter++) { 2 console.log(loopCounter); 3}
JavaScript is a zero index language and so this starts loopCounter
at 0, runs while loopCounter
is less than 5 and each time the loop completes an iteration loopCounter
is increased by 1.
Each iteration of the loop will log out the value of loopCounter
.
You can use this to iterate through an array by using the loop counter as the index for each element of the array.
1let family = ["Ben", "Emily", "Saj", "Vahid"]; 2 3for (let loopCounter = 0; loopCounter < 4; loopCounter++) { 4 console.log(family[loopCounter]); 5}
Loop counter will increase by one each time and then we use loopCounter
to access an element in the array family[loopCounter]
.
If you want to make sure your 'for' loop runs for the number of elements in the array, you can use the array's length property as the stop condition.
While
'While' loops are like 'for' loops, however they are more prone to getting stuck in an infinite loop.
They are rarely used in programming unless "running forever" is a desired trait, like running the rendering engine for a game or constantly checking to see if something has happened.
For Of
The problem with loops is making sure they run the correct number of times. 'Off by one' errors are very common in programming and usually occur when you are looking at each element of an array and get your stop condition wrong.
In the example about the <=
condition causes a one element overrun and so the final iteration tries to access ages[4]
which of course in a 0 indexed array isn't valid. Only indexes 0, 1, 2 and 3 are valid.
Well this is the problem that a for ... of
loop handles.
This loops over the items in the array without you needing to worry about the index or loop count or anything like that.
This is a more declarative way of programming, you are telling the computer what you want it to do rather than exactly how to do it.
Break
If you want to stop looping before your stop condition has been met then you can break
the loop.
Continue
If you want to end the current iteration of a loop but carry on through the rest then you can continue
.