Transcript from the "Loops" Lesson
[00:03:39] In our previous example, with our reps, We had a counter called rep. That we wanted the loop to keep going as long as rep is less than 10. So we notice it doesn't get to the value actually 10 cuz we don't have that less than or equals, and we're adding 1 to the rep each time.
[00:04:05] Now, I haven't really talked about this plus equals operator here, but any guess what that's doing, plus equals?
>> Increment the value of the counter.
>> Exactly, it increments a value. So let's say I have a dogs, a count of dogs, right now I have zero dogs, I would like a dog.
[00:04:47] So now, dogs is 2 and + = is a quick way of doing that same thing. Cool. Okay, so we see that + = a lot in our for loops. But you might be thinking, wow, this is complicated. There's a lot of work to do to just like, increase a number by one every time or something like that.
[00:05:38] So for example, if I have an array of numbers and I want to log out each of those numbers from my array. With a traditional for loop, I have to do it real complicated as, US coders and Aval Levine both do not like. I have to declare a counter, in this case, it's an index.
[00:05:56] It's gonna start at zero. I have to say, keep going as long as the count index is less than the length of the numbers array, cuz that's how we'll know we've reached the end of the array. And this is another fancy little operator, I++ is also incrementing this value.
[00:06:17] So, this is a another incrementer operator here. And that whole thing we can replace with this nice little pithy for of loop that says for, let number n of the numbers array log the value n. So these are both going to do the same thing, but they're doing it in two different ways, so our for of loop, sorry our traditional for loop.
[00:06:50] We've got our numbers, and then we're gonna log out. We're gonna iterate over the indices in the numbers array, and then we're gonna use that index to pull out each thing in the array. But because we hate typing stuff, we probably when we're trying to get things out of an array like this, we're probably going to use oops.
[00:07:14] I'm probably going to use our shorter friend, the for of loop, which is going to say for each item of the array numbers. And we're gonna name that item n, log that item out, and it's gonna do the same thing in way less characters of typing code. Cool.
[00:08:10] So, we said that we can do this for items in an array. We can also use it for characters in a string. So for example, if I do for (let char of, the string "ALOHA"), and console.log my (char), we're going to get, Each character logged out on its own line.