Looping Arrays, Breaking and Continuing | JavaScript 🔥 | Lecture 044
Summary
TLDRThe script provides a step-by-step walkthrough of using for loops in JavaScript to iterate through arrays. It starts with a simple example of logging array elements to the console, explaining the logic and syntax behind constructing a basic for loop. It then covers more advanced topics like dynamically setting loop conditions based on array length, constructing new arrays from existing ones, and using continue and break statements to control loop execution flow. The goal is to provide a comprehensive overview of leveraging for loops to efficiently process array data in JavaScript.
Takeaways
- 😀 For loops are commonly used to iterate over arrays
- 👉 We can log each element of an array to the console using a for loop
- 📝 The condition of the for loop should check that the counter stays below the length of the array
- 🧮 We can perform operations on each element of an array using values from the array in the for loop
- 🔢 We started the counter at 0 because arrays are zero-indexed when accessing elements
- 🆕 We can create a new array and fill it based on values from another array using a for loop
- ➕ We can use the .push() method to add elements to an array within a loop
- ❗️ The continue statement skips the current iteration and moves to the next one
- 🛑 The break statement stops the entire loop execution
- 🎉 Understanding how to loop arrays with for loops is very important
Q & A
What is a common use case for for loops?
-A very common use of for loops is to iterate through the elements in an array.
How do you loop through an array with a for loop?
-You need to start a counter at 0, set the loop condition to be that the counter is less than the array length, and increment the counter each iteration.
Why is using the array length better than hardcoding a number for the loop condition?
-Using the array length automatically adjusts if new items are added, instead of having to manually update a hardcoded length.
How can you fill a new array based on values from another array?
-You can use a for loop on the first array, and in each iteration, calculate values to push into the new array.
What does the continue statement do?
-Continue exits the current iteration of the loop and jumps to the next iteration.
What does the break statement do?
-Break exits the whole loop completely, terminating it early.
How could you use continue or break in a loop?
-You could use continue to skip some iterations based on a condition, or use break to stop the loop when you have reached some target condition.
What are the key components of a for loop?
-The key components are the counter initialization, the loop condition, the code executed in the loop body, and updating the counter.
How do you access the current element when looping an array?
-You use the array name and the current counter variable, like array[i], to access the current element.
Why is looping arrays important in programming?
-It allows you to perform the same operations or calculations on every element without repetitive code.
Outlines
😀 Introducing For Loops to Iterate Arrays
This paragraph introduces the for loop as a useful way to iterate through arrays. It shows an example of logging each element of the Jonas array to the console using a counter variable 'i' that starts at 0 and increments each iteration. The condition checks that i stays below the length of the array. This allows accessing each element by index.
😉 Dynamically Getting Array Length
This paragraph improves on the previous example by dynamically getting the array length instead of hardcoding it. This way if elements are added to the array, the loop will still work without needing to manually update the condition. The key is to use Jonas.length instead of a hardcoded number.
📝 Filling a New Array from Existing Array
This paragraph shows how to fill values into a new empty array based on iterating over an existing array. Two options are demonstrated: 1) Directly assign values from Jonas array into Types array using index. 2) Push values into Types array. The concepts reinforce how to construct arrays from loops.
💡 Using Continue and Break in Loops
This paragraph introduces the continue and break statements for controlling loop execution. Continue exits the current iteration and goes to the next one, while break completely terminates the whole loop. Examples are shown for only logging strings from an array with continue and stopping after the first number with break.
🧮 Calculate Ages from Birth Years
This paragraph ties concepts together into a practical example. It loops through an array of birth years, calculates the age based on the current year, and fills the ages into a new array. This demonstrates a common real-world use case for iterating arrays with a loop.
Mindmap
Keywords
💡for loop
💡array
💡counter variable
💡condition
💡iteration
💡continue
💡break
💡push
💡length
💡index
Highlights
The for loop is commonly used to iterate over arrays
Arrays in JavaScript are zero-indexed, so we start the counter at 0 to get the first element
The condition checks that the counter stays below the length of the array to avoid errors
We can use the counter variable to access each element of the array in the loop
Calculating the length of the array instead of hardcoding avoids errors when the array changes
We constructed a new array based on values from an existing array in the loop
The push() method adds elements to the end of an array
Loops allow us to perform operations on array elements instead of just the array
Continue skips the current iteration and moves to the next one
Break exits the whole loop completely, not just the current iteration
Continue and break allow selective execution of loop iterations
Understanding how to iterate arrays with loops is very important
We can perform calculations on each element by accessing via the counter
The loop fills up a new array with values derived from an existing array
Being able to filter array elements is a useful application of continue
Transcripts
Let's now explore some more features
of the for loop
and also create a somewhat more useful example.
And one of the most used applications
of for loops is to loop through a race.
So let's get back the array that we were using before.
So where is that?
So, I mean the one
where we talked about objects.
Yeah, this one.
So go to this lecture about introduction to objects
and then grab this Jonas array.
And maybe you didn't write it back then
but then you can just write it, right now.
Okay, and so now we can use a for loop
to loop through this array.
And let's say for now that we wanted to individually
log every element of the array to the console.
So very simple.
All we want to do is to log these five elements here.
So let's write a for loop.
And as always, we start with the counter.
So let...
And now a traditional counter variable name has been I
for a long time.
And so let's use that here as well.
So just I, and this time we need to start it at zero.
And that's because the array is zero based
when it comes to reading elements out of the array.
Remember, and this will make sense once we actually write
the code of this loop.
Let's now actually skip the condition for now.
So we're gonna deal with that a little bit later.
And so now updating the counter
is gonna work exactly the same as before.
So since we want to log all of the elements
we need to update the counter variable simply by one.
And so again, we use ++, okay.
And now let's write or loop here itself.
So console.log,
and remember all we want to log to the console
is each element of the array.
And so without a loop
we would write that like this,
so Jonas zero.
Right?
And then let's do that outside.
So we would do this
this, and then all the way to
number four.
All right.
So let's comment is out
but this is helpful to see what kind of code
we want to achieve.
So again, we want to start at Jonas zero
which is the first element.
Jonas one is this one, then two, three, and four.
And so that's the reason why we started the counter at zero
because that's the first element that we want to get.
It's Jonas zero.
And so here, instead of hard coding to zero,
of course, we are going to use or counter variable.
So, and that's I.
And now the trickiest part here, is the condition.
And so that's why we left it for the end,
but now we need to actually tackle it.
So for how long do we want to keep this loop running?
Well, it should run when I is zero.
Right?
It should also run when it's one two, three, and four.
Because four is the last element.
But when it's five, it's no longer run.
Right?
And that's because Jonas at five does not exist.
Let's just write that,
does not exist.
And so that means that the I counter variable
should always stay below five.
So let's write that here.
So I should stay
below five.
And so with this,
as soon as the counter variable is updated to five
then the next iteration of the loop will not run anymore.
So let's try this.
And here it's of course not Jonas
it's Jonas array.
So let's actually change the name up here,
in the array itself.
Try that again.
And yeah, we get a log of each of the elements
in the array.
So all of the five of them.
Great.
But there's actually still one problem with this,
which is that we hard-coded the length of the array
here with five.
So let's now say
that we add another element,
let's say just true.
And so if we try this now,
do you think that's true will be logged here as well?
Well, it will not.
Because of course we are still telling JavaScript
that I should stay below five.
And so it will not print the array at position number five,
which does now exist.
So now we do have Jonas at position five, right?
And so the solution to this,
is to not hard code the value here
but to compute this value.
So basically to get it from JavaScript itself.
And how can we get this number?
Well, actually this five is simply the length of the array
right?
Not of this one anymore, but off the original one.
So this array has a length of five.
And so five is exactly the number that we put here.
And so we can simply replace the hard-coded value
with a dynamically calculated one.
and that's Jonas.length.
Remember?
So,
let's try that.
And indeed it still works.
And if I now go back to adding something else
like true,
then Jonas.length
will now be six.
And that of course happens automatically.
And we don't have to manually change any code
in that loop.
So now we did true also appears here in our luck.
Great.
Let's now also log something else here.
Let's say the type of the variable.
So type of Jonas i.
And I hope that this part here makes sense.
So the fact that we're using the counter variable here
to retrieve all the elements of the array.
So now let's say, so string,
string, number, string, object.
So remember how I said that an array is in fact an object
and here we have the proof of that.
And then finally the last one is of course a boolean.
Okay.
So I hope that this logic here made sense.
And so this is in a nutshell,
how we loop race using the for loop.
Now, what we did here, was only to read values
from an array.
But now let's also at the same time,
create a new array which will contain
this type of each of the elements.
So basically this, all right?
So again, what I want to do now
is to create a new array which will contain all the types
for all these elements.
And if that sounds a little bit useless,
then just keep in mind that these are all just
educational exercises.
So I designed them to show you how these different features
of the language work.
So in real world, we would probably not create an array
with types of variables.
But this is excellent to show you,
how to create a new array based on the values
of one original array.
So to do that we start by creating
a new empty array outside of the loop.
And let's do that here, after this one.
So I will call this one types.
And now I think this is something we didn't do before,
which is to simply create an empty array.
And all we have to do is to basically create an array
with the usual syntax, but without any element inside of it.
And so now we have to go here to the same loop
because this new array types will be based
on the Jonas array.
So it's gonna have the same length.
And so we can use the exact same loop
that we used to read data from the Jonas loop
also to construct this new types array.
So let's say types,
at position I, should be equal to
type of Jonas
at position I.
And remember that this works
because we can essentially do this.
So we could do it again without the loop
and say types zero
is equals string.
So this would work, right?
And so of course it also works with the
index number here dynamically.
And so that's exactly what we're doing here
in the exact same way as we read data
from the Jonas array,
right?
So in iteration zero,
we will have type zero equals type of Jonas zero.
Then in the next iteration,
we will have types one
equals type of Jonas one
and then two, three, four, and five.
All right.
So just to see if that works
let's then log to the console,
this newly created
or to be more accurate, this newly filled array.
So let's see.
And indeed now we get this array
which has exactly the types that we can see here as well.
So string, string, number,
string, object, and boolean.
So these six that we also have here
which means that we achieved our goal here.
Now, this is just one way
of filling an array.
And let me write that down here,
filling the types array.
And here we do basically reading
from Jonas array.
But this is just one way of doing it.
So let's comment out this one
and do it in another way.
And do you remember how to add elements
to an array in another way?
Well, we could use the push method, right?
So that would be types.push.
And remember that push
adds a new element to the end of the array.
And so here, we now need to pass in the element
that we do want to add on to the array.
And so that's again
type of Jonas
at position I.
So off the current counter.
And so if we try this now again,
we should get to the same.
And it's important that we add the new element
to the end of array and not to the beginning.
So we really need to use pushier and not unshift.
So I think that this way of doing it here
is actually a little bit cleaner.
But if you prefer this first way here
then of course you can just use that one as well.
But what matters here,
is that we really understood the logic
of how to construct all the different parts of this for loop
in order to loop the array.
So it starts the counter being zero
because that's the first element of the array.
And then this condition here
which specifies that the current index always needs to stay
below the length of the array that we're looping through.
And then in the loop itself
we always get the current element using the current counter.
Which is gonna go from zero
to the length of the array minus one basically.
All right.
And to make sure we really get this
let's try another, maybe more practical example.
So let's go back to having an array of birth years.
So 1991,
2007,
let's say 1969
and 2020.
And now what we want to do is to calculate the ages
for all these four birth years here.
And we want to store them in a new array.
And that's a very common type of operation,
which we actually already did before
but without using loops.
So essentially that's what we did
in the tip calculator challenge.
So,
yeah, here.
So here we had an array of three bills
and then we manually calculated the tip for each of them.
So manually we specified index zero,
one and two,
and created a new array based on these values.
But in the real world, we would have used a loop to do that.
And so that's what we will do now.
Okay.
Just with another, a bit more simple example.
Years is the array which contains the birth years,
and now let's create another
and again, empty array, which will then hold the ages.
And so what we're gonna do now
is to loop through years and then fill up these ages array.
So four,
and then once more,
let's define the counter at zero
for the same reasons that we did it before.
And it's not a problem that discounter variable here
has exactly the same name.
Then the condition is also gonna be the same.
And actually the whole loop
always kind of looks the same,
when we loop over an array.
So now here the difference
is that it's of course, years.length.
And then at the end,
we as always increased the counter by one.
And now what we need to do is to calculate the age
of the current year.
So that's gonna be,
2037.
So as always that's the year that we're currently in,
let's say, and then minus the current birth here.
So how do we get that?
We say years, at the current loop position.
Okay?
So that's nothing new.
I hope now at this point, okay.
So we have this calculation now
and now we want to add it to this new empty array.
So we say we want to push it,
to that array.
And so we use the push method to do that.
So ages.push.
And so this is the value
that we want to push into this empty array.
And that's actually it.
So let's check it out in a console
and
here we go.
So just to confirm,
2037 minus 1991 is of course 46.
And that's just do it with 27 as well,
2007 I mean.
And so that's 30, which is this one.
And so this array result, is correct indeed.
So what we essentially did is this.
We cannot do an operations
between simple values and an array.
So that I showed you earlier, right?
We can not do 2037
minus the years array.
That will just give us not a number.
And so here in this loop,
we basically did it individually.
So we did to calculation one by one.
In each iteration of the loop
we calculated 2037
minus this year and then added it
to the first position in the ages array.
Then we did 2037 minus this
and put it at the end of the ages array again.
And then the same for this one and for 2020.
Great.
So that is a very very useful
and important application of the for loop.
And now to finish,
let's learn about two important statements
for loops.
And that's the continue and to break statement.
Let me just write that here,
continue and break.
And let's start with continue.
So continue is to exit the current iteration of the loop
and continue to the next one.
On the other hand, break is used
to completely terminate the whole loop.
So let's see two quick examples for that.
And let's go back to actually this loop
that we had here.
Where we looped this Jonas array.
So I will just copy this,
because we already learned how to loop through the array.
And now I'm just interested in showing you
how continue and to break a work.
So let me delete this
and this as well.
And now let's say that for some reason,
we only wanted to print elements to the array
that are strings.
And the continue statement is perfect for this.
Because again,
with continue we can exit the current iteration of the loop.
So what we can do here, is to say,
if the type of the current element
so of Jonas I,
is not a string,
then continue.
And so that's how we write the continue statement.
It's really just this continue keyword.
So again, what we want to do here,
is to only log strings to the console.
Which means that everything else,
should basically be skipped.
And that's what we do here.
So we say, if the type of the current element,
so that's this one here.
So if the type of the current element
is not a string then continue.
Which again means,
that the current iteration of the loop is exited,
and then the next one starts immediately.
So let's just write some other note here
to the console just so we know
what we're doing here, like
all the strings
because otherwise the output here
is gonna start to look a little bit confusing.
But anyway, let's test this now.
And indeed, we only get strings now.
So these three are strings
and all the other ones are not strings.
So this number, this array and this boolean,
so they will now not get printed.
Because we basically skipped them.
For example, that eight number,
which is 46 here.
So the third element, does have to type number here.
Right?
So it's not a string.
And so this year will be true
because of course number is different than string.
And so this is true.
And so this code here, will run.
And what continue will do
is that it will immediately exit the current iteration.
And so this line of code here,
will not be executed in the current iteration.
It will not even be reached.
Okay.
And now finally, let me just show you how break works.
And remember that what break does
is to completely terminate the whole loop.
So not just the current iteration.
So what we want to do now, is to log no other elements
after we found a number.
So essentially after a number is found
which will be this 46 here,
nothing else should be printed.
So let's do that.
And i will again, copy all of this.
And so let's say here
break
with number.
So let's translate a logic that we just said into the code.
So as soon as a number is found,
we want to break the loop.
So, our if condition here should be
type of Jonas I,
so the current element,
if it's equal to a number,
so now that's number then break.
Now, okay.
Let's see the result here.
And indeed, that's exactly what we wanted.
So after the first number is found
which is this 46 here,
nothing else is printed.
So in this iteration where the number is found
not even this line of code is printed anymore
and then the loop is terminated completely.
All right.
Now this might not sound very practical,
but believe me there are some important use cases
for continue and break.
It's just hard to create some small and isolated
code examples to show you just how useful they can be.
But anyway I wanted to let you know
that continue and break exist.
But the most important takeaway from this lecture,
is definitely to understand,
how we can loop through a race
using this kind of logic here.
Okay, so this one here is really important
that you understand this snippet of code.
5.0 / 5 (0 votes)