So I’ve made quite a bit of progress but I’m currently puzzled by something: loops.
TLDR at the bottom:
Here’s what I understand from it all:
a) i is the equivalent of iterator.
b) the for
loop is used to repeat a code.
c) the iterator expression appears in all three expressions that make up the for
loop.
d) The start parts for the loop are: initialization, stopping condition and iteration statement.
e) Initialization: where the loop begins, the starting point if you will.
f) Stopping condition: when this condition is met, the loop will stop.
g) Iteration statement: that’s how the loop with make its modifications with lack of better words.
h) from what I can tell, there’s ++ and – so far for the iteration statement. I would imagine there are more but I haven’t learned them so far.
i) ++ and – mean add one and subtract one, respectively.
j) In the following example:
The loop will begin at 0 (initializer), then go up by 1 at a time (iteration statement) until it reaches a number lower than 4 (stopping condition).
k) console.log
would record the result of this: 0, 1, 2 and 3.
l) We can loop through an array. That means to perform the looping operation on each element of the array.
m) In order to loop through an array, we need to use the .length
property in its condition.
n) In the following example:
We’re dealing with an array index so I need to use [n] to identify which array I’m referring to. In other words, [0] is the bear, [1] the Sloth and [2] the Sea lion.
o) Here a loop is introduced followed by the usual brackets ( ). Then a variable is declare as being the iterator which is a bit more confusing as I didn’t realize I had to have a variable to use a loop. So now I’m feeling less solid but I carry on. Then I realize i
here is just name of the variable so no need to fret about it. The next i
that comes after is the stop condition.
p) So the initialization is at the string ‘Grizzly Bear’. Then it says animals.length
and the increment is +1 because of ++.
TLDR: The .length
sort of puzzles me.
Remember that arrays are zero-indexed, the index of the last element of an array is equivalent to the length of that array minus 1.
It seems like there’s on indication as for when the loop to stop in this case. Could someone explain?