Looping Arrays, Breaking and Continuing | JavaScript đŸ”„ | Lecture 044

The Coding Classroom
8 Apr 202322:02

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

00:00

😀 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.

05:01

😉 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.

10:02

📝 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.

15:02

💡 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.

20:03

🧼 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

A for loop allows you to repeat a block of code a certain number of times. It is used in the video to loop through arrays and perform an action on each element. For example, logging array elements to the console or calculating ages based on birth years in an array.

💡array

An ordered collection of data. Arrays are iterated through using for loops in the video. The video shows examples of looping through an array to log elements, create a new array based on values, and perform calculations on each element.

💡counter variable

A variable used to track each iteration of a loop. Typically called 'i', initialized to 0 to match array index values, and incremented each iteration. Determines current element in loop iteration.

💡condition

Part of for loop syntax that determines how long loop runs. Typically checks if counter variable is less than array length, so full array is iterated through.

💡iteration

Each repeat of the loop code block. Continues based on condition check. Current value available through counter variable.

💡continue

Keyword to exit current iteration of loop and immediately start next iteration. Used to conditionally skip iterations.

💡break

Keyword to completely terminate and exit whole loop structure. Used after condition is met within loop.

💡push

Array method to append new element to end of array. Used in video to add calculated values to new results array.

💡length

Property on arrays holding number of elements. Used dynamically in loop condition instead of hard-coded value.

💡index

Position number of each element in an array, starts counting at 0. Accessed within loop using counter variable to retrieve current element.

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

play00:01

Let's now explore some more features

play00:03

of the for loop

play00:05

and also create a somewhat more useful example.

play00:10

And one of the most used applications

play00:12

of for loops is to loop through a race.

play00:16

So let's get back the array that we were using before.

play00:22

So where is that?

play00:26

So, I mean the one

play00:28

where we talked about objects.

play00:30

Yeah, this one.

play00:31

So go to this lecture about introduction to objects

play00:35

and then grab this Jonas array.

play00:37

And maybe you didn't write it back then

play00:40

but then you can just write it, right now.

play00:45

Okay, and so now we can use a for loop

play00:47

to loop through this array.

play00:50

And let's say for now that we wanted to individually

play00:54

log every element of the array to the console.

play00:57

So very simple.

play00:59

All we want to do is to log these five elements here.

play01:04

So let's write a for loop.

play01:08

And as always, we start with the counter.

play01:11

So let...

play01:12

And now a traditional counter variable name has been I

play01:16

for a long time.

play01:18

And so let's use that here as well.

play01:20

So just I, and this time we need to start it at zero.

play01:26

And that's because the array is zero based

play01:28

when it comes to reading elements out of the array.

play01:31

Remember, and this will make sense once we actually write

play01:36

the code of this loop.

play01:38

Let's now actually skip the condition for now.

play01:41

So we're gonna deal with that a little bit later.

play01:45

And so now updating the counter

play01:47

is gonna work exactly the same as before.

play01:50

So since we want to log all of the elements

play01:53

we need to update the counter variable simply by one.

play01:57

And so again, we use ++, okay.

play02:01

And now let's write or loop here itself.

play02:05

So console.log,

play02:07

and remember all we want to log to the console

play02:10

is each element of the array.

play02:12

And so without a loop

play02:14

we would write that like this,

play02:17

so Jonas zero.

play02:19

Right?

play02:20

And then let's do that outside.

play02:23

So we would do this

play02:25

this, and then all the way to

play02:30

number four.

play02:33

All right.

play02:34

So let's comment is out

play02:36

but this is helpful to see what kind of code

play02:39

we want to achieve.

play02:41

So again, we want to start at Jonas zero

play02:44

which is the first element.

play02:46

Jonas one is this one, then two, three, and four.

play02:50

And so that's the reason why we started the counter at zero

play02:54

because that's the first element that we want to get.

play02:57

It's Jonas zero.

play02:59

And so here, instead of hard coding to zero,

play03:01

of course, we are going to use or counter variable.

play03:05

So, and that's I.

play03:07

And now the trickiest part here, is the condition.

play03:11

And so that's why we left it for the end,

play03:14

but now we need to actually tackle it.

play03:16

So for how long do we want to keep this loop running?

play03:21

Well, it should run when I is zero.

play03:24

Right?

play03:24

It should also run when it's one two, three, and four.

play03:29

Because four is the last element.

play03:32

But when it's five, it's no longer run.

play03:35

Right?

play03:35

And that's because Jonas at five does not exist.

play03:40

Let's just write that,

play03:48

does not exist.

play03:52

And so that means that the I counter variable

play03:55

should always stay below five.

play03:58

So let's write that here.

play04:01

So I should stay

play04:03

below five.

play04:05

And so with this,

play04:06

as soon as the counter variable is updated to five

play04:10

then the next iteration of the loop will not run anymore.

play04:15

So let's try this.

play04:18

And here it's of course not Jonas

play04:20

it's Jonas array.

play04:22

So let's actually change the name up here,

play04:26

in the array itself.

play04:28

Try that again.

play04:29

And yeah, we get a log of each of the elements

play04:34

in the array.

play04:35

So all of the five of them.

play04:38

Great.

play04:39

But there's actually still one problem with this,

play04:42

which is that we hard-coded the length of the array

play04:45

here with five.

play04:47

So let's now say

play04:48

that we add another element,

play04:51

let's say just true.

play04:53

And so if we try this now,

play04:54

do you think that's true will be logged here as well?

play04:59

Well, it will not.

play05:01

Because of course we are still telling JavaScript

play05:04

that I should stay below five.

play05:07

And so it will not print the array at position number five,

play05:10

which does now exist.

play05:12

So now we do have Jonas at position five, right?

play05:17

And so the solution to this,

play05:19

is to not hard code the value here

play05:21

but to compute this value.

play05:23

So basically to get it from JavaScript itself.

play05:27

And how can we get this number?

play05:29

Well, actually this five is simply the length of the array

play05:34

right?

play05:35

Not of this one anymore, but off the original one.

play05:39

So this array has a length of five.

play05:41

And so five is exactly the number that we put here.

play05:44

And so we can simply replace the hard-coded value

play05:48

with a dynamically calculated one.

play05:51

and that's Jonas.length.

play05:55

Remember?

play05:56

So,

play05:58

let's try that.

play06:00

And indeed it still works.

play06:02

And if I now go back to adding something else

play06:05

like true,

play06:06

then Jonas.length

play06:07

will now be six.

play06:09

And that of course happens automatically.

play06:11

And we don't have to manually change any code

play06:14

in that loop.

play06:17

So now we did true also appears here in our luck.

play06:21

Great.

play06:23

Let's now also log something else here.

play06:25

Let's say the type of the variable.

play06:28

So type of Jonas i.

play06:32

And I hope that this part here makes sense.

play06:35

So the fact that we're using the counter variable here

play06:37

to retrieve all the elements of the array.

play06:42

So now let's say, so string,

play06:45

string, number, string, object.

play06:48

So remember how I said that an array is in fact an object

play06:51

and here we have the proof of that.

play06:54

And then finally the last one is of course a boolean.

play06:58

Okay.

play06:59

So I hope that this logic here made sense.

play07:03

And so this is in a nutshell,

play07:05

how we loop race using the for loop.

play07:08

Now, what we did here, was only to read values

play07:11

from an array.

play07:12

But now let's also at the same time,

play07:15

create a new array which will contain

play07:18

this type of each of the elements.

play07:21

So basically this, all right?

play07:23

So again, what I want to do now

play07:25

is to create a new array which will contain all the types

play07:29

for all these elements.

play07:32

And if that sounds a little bit useless,

play07:35

then just keep in mind that these are all just

play07:38

educational exercises.

play07:40

So I designed them to show you how these different features

play07:44

of the language work.

play07:46

So in real world, we would probably not create an array

play07:50

with types of variables.

play07:52

But this is excellent to show you,

play07:54

how to create a new array based on the values

play07:57

of one original array.

play07:59

So to do that we start by creating

play08:01

a new empty array outside of the loop.

play08:05

And let's do that here, after this one.

play08:09

So I will call this one types.

play08:12

And now I think this is something we didn't do before,

play08:16

which is to simply create an empty array.

play08:18

And all we have to do is to basically create an array

play08:22

with the usual syntax, but without any element inside of it.

play08:27

And so now we have to go here to the same loop

play08:30

because this new array types will be based

play08:33

on the Jonas array.

play08:34

So it's gonna have the same length.

play08:36

And so we can use the exact same loop

play08:38

that we used to read data from the Jonas loop

play08:42

also to construct this new types array.

play08:46

So let's say types,

play08:49

at position I, should be equal to

play08:53

type of Jonas

play08:57

at position I.

play08:59

And remember that this works

play09:01

because we can essentially do this.

play09:04

So we could do it again without the loop

play09:07

and say types zero

play09:10

is equals string.

play09:13

So this would work, right?

play09:15

And so of course it also works with the

play09:18

index number here dynamically.

play09:21

And so that's exactly what we're doing here

play09:23

in the exact same way as we read data

play09:25

from the Jonas array,

play09:29

right?

play09:30

So in iteration zero,

play09:32

we will have type zero equals type of Jonas zero.

play09:37

Then in the next iteration,

play09:39

we will have types one

play09:41

equals type of Jonas one

play09:44

and then two, three, four, and five.

play09:47

All right.

play09:49

So just to see if that works

play09:52

let's then log to the console,

play09:54

this newly created

play09:56

or to be more accurate, this newly filled array.

play10:01

So let's see.

play10:03

And indeed now we get this array

play10:06

which has exactly the types that we can see here as well.

play10:09

So string, string, number,

play10:11

string, object, and boolean.

play10:13

So these six that we also have here

play10:16

which means that we achieved our goal here.

play10:19

Now, this is just one way

play10:21

of filling an array.

play10:25

And let me write that down here,

play10:27

filling the types array.

play10:30

And here we do basically reading

play10:35

from Jonas array.

play10:37

But this is just one way of doing it.

play10:40

So let's comment out this one

play10:42

and do it in another way.

play10:44

And do you remember how to add elements

play10:46

to an array in another way?

play10:49

Well, we could use the push method, right?

play10:54

So that would be types.push.

play10:57

And remember that push

play10:59

adds a new element to the end of the array.

play11:02

And so here, we now need to pass in the element

play11:05

that we do want to add on to the array.

play11:08

And so that's again

play11:09

type of Jonas

play11:12

at position I.

play11:14

So off the current counter.

play11:16

And so if we try this now again,

play11:19

we should get to the same.

play11:21

And it's important that we add the new element

play11:24

to the end of array and not to the beginning.

play11:27

So we really need to use pushier and not unshift.

play11:31

So I think that this way of doing it here

play11:34

is actually a little bit cleaner.

play11:36

But if you prefer this first way here

play11:39

then of course you can just use that one as well.

play11:42

But what matters here,

play11:44

is that we really understood the logic

play11:46

of how to construct all the different parts of this for loop

play11:50

in order to loop the array.

play11:52

So it starts the counter being zero

play11:54

because that's the first element of the array.

play11:57

And then this condition here

play12:00

which specifies that the current index always needs to stay

play12:04

below the length of the array that we're looping through.

play12:07

And then in the loop itself

play12:09

we always get the current element using the current counter.

play12:13

Which is gonna go from zero

play12:15

to the length of the array minus one basically.

play12:19

All right.

play12:21

And to make sure we really get this

play12:23

let's try another, maybe more practical example.

play12:27

So let's go back to having an array of birth years.

play12:31

So 1991,

play12:34

2007,

play12:35

let's say 1969

play12:38

and 2020.

play12:42

And now what we want to do is to calculate the ages

play12:45

for all these four birth years here.

play12:47

And we want to store them in a new array.

play12:50

And that's a very common type of operation,

play12:53

which we actually already did before

play12:56

but without using loops.

play12:58

So essentially that's what we did

play13:00

in the tip calculator challenge.

play13:05

So,

play13:08

yeah, here.

play13:09

So here we had an array of three bills

play13:12

and then we manually calculated the tip for each of them.

play13:15

So manually we specified index zero,

play13:18

one and two,

play13:21

and created a new array based on these values.

play13:25

But in the real world, we would have used a loop to do that.

play13:29

And so that's what we will do now.

play13:32

Okay.

play13:33

Just with another, a bit more simple example.

play13:37

Years is the array which contains the birth years,

play13:40

and now let's create another

play13:42

and again, empty array, which will then hold the ages.

play13:46

And so what we're gonna do now

play13:48

is to loop through years and then fill up these ages array.

play13:52

So four,

play13:55

and then once more,

play13:56

let's define the counter at zero

play14:00

for the same reasons that we did it before.

play14:03

And it's not a problem that discounter variable here

play14:07

has exactly the same name.

play14:09

Then the condition is also gonna be the same.

play14:11

And actually the whole loop

play14:13

always kind of looks the same,

play14:15

when we loop over an array.

play14:17

So now here the difference

play14:19

is that it's of course, years.length.

play14:22

And then at the end,

play14:24

we as always increased the counter by one.

play14:28

And now what we need to do is to calculate the age

play14:31

of the current year.

play14:33

So that's gonna be,

play14:34

2037.

play14:36

So as always that's the year that we're currently in,

play14:39

let's say, and then minus the current birth here.

play14:43

So how do we get that?

play14:46

We say years, at the current loop position.

play14:50

Okay?

play14:51

So that's nothing new.

play14:52

I hope now at this point, okay.

play14:55

So we have this calculation now

play14:57

and now we want to add it to this new empty array.

play15:01

So we say we want to push it,

play15:03

to that array.

play15:04

And so we use the push method to do that.

play15:07

So ages.push.

play15:12

And so this is the value

play15:13

that we want to push into this empty array.

play15:16

And that's actually it.

play15:20

So let's check it out in a console

play15:25

and

play15:28

here we go.

play15:30

So just to confirm,

play15:31

2037 minus 1991 is of course 46.

play15:37

And that's just do it with 27 as well,

play15:40

2007 I mean.

play15:42

And so that's 30, which is this one.

play15:44

And so this array result, is correct indeed.

play15:48

So what we essentially did is this.

play15:51

We cannot do an operations

play15:53

between simple values and an array.

play15:56

So that I showed you earlier, right?

play15:58

We can not do 2037

play16:00

minus the years array.

play16:03

That will just give us not a number.

play16:06

And so here in this loop,

play16:08

we basically did it individually.

play16:10

So we did to calculation one by one.

play16:13

In each iteration of the loop

play16:14

we calculated 2037

play16:17

minus this year and then added it

play16:19

to the first position in the ages array.

play16:21

Then we did 2037 minus this

play16:24

and put it at the end of the ages array again.

play16:27

And then the same for this one and for 2020.

play16:31

Great.

play16:32

So that is a very very useful

play16:34

and important application of the for loop.

play16:39

And now to finish,

play16:40

let's learn about two important statements

play16:42

for loops.

play16:44

And that's the continue and to break statement.

play16:47

Let me just write that here,

play16:49

continue and break.

play16:52

And let's start with continue.

play16:55

So continue is to exit the current iteration of the loop

play17:00

and continue to the next one.

play17:02

On the other hand, break is used

play17:04

to completely terminate the whole loop.

play17:08

So let's see two quick examples for that.

play17:11

And let's go back to actually this loop

play17:13

that we had here.

play17:15

Where we looped this Jonas array.

play17:18

So I will just copy this,

play17:20

because we already learned how to loop through the array.

play17:24

And now I'm just interested in showing you

play17:25

how continue and to break a work.

play17:29

So let me delete this

play17:31

and this as well.

play17:33

And now let's say that for some reason,

play17:36

we only wanted to print elements to the array

play17:39

that are strings.

play17:40

And the continue statement is perfect for this.

play17:44

Because again,

play17:45

with continue we can exit the current iteration of the loop.

play17:49

So what we can do here, is to say,

play17:53

if the type of the current element

play17:58

so of Jonas I,

play18:03

is not a string,

play18:06

then continue.

play18:10

And so that's how we write the continue statement.

play18:13

It's really just this continue keyword.

play18:16

So again, what we want to do here,

play18:18

is to only log strings to the console.

play18:22

Which means that everything else,

play18:23

should basically be skipped.

play18:25

And that's what we do here.

play18:27

So we say, if the type of the current element,

play18:31

so that's this one here.

play18:33

So if the type of the current element

play18:35

is not a string then continue.

play18:38

Which again means,

play18:39

that the current iteration of the loop is exited,

play18:43

and then the next one starts immediately.

play18:46

So let's just write some other note here

play18:50

to the console just so we know

play18:52

what we're doing here, like

play18:56

all the strings

play18:58

because otherwise the output here

play19:00

is gonna start to look a little bit confusing.

play19:04

But anyway, let's test this now.

play19:07

And indeed, we only get strings now.

play19:10

So these three are strings

play19:12

and all the other ones are not strings.

play19:15

So this number, this array and this boolean,

play19:18

so they will now not get printed.

play19:21

Because we basically skipped them.

play19:23

For example, that eight number,

play19:25

which is 46 here.

play19:27

So the third element, does have to type number here.

play19:31

Right?

play19:32

So it's not a string.

play19:34

And so this year will be true

play19:36

because of course number is different than string.

play19:39

And so this is true.

play19:41

And so this code here, will run.

play19:43

And what continue will do

play19:45

is that it will immediately exit the current iteration.

play19:48

And so this line of code here,

play19:49

will not be executed in the current iteration.

play19:52

It will not even be reached.

play19:55

Okay.

play19:56

And now finally, let me just show you how break works.

play20:00

And remember that what break does

play20:02

is to completely terminate the whole loop.

play20:05

So not just the current iteration.

play20:07

So what we want to do now, is to log no other elements

play20:11

after we found a number.

play20:14

So essentially after a number is found

play20:16

which will be this 46 here,

play20:18

nothing else should be printed.

play20:22

So let's do that.

play20:23

And i will again, copy all of this.

play20:27

And so let's say here

play20:31

break

play20:33

with number.

play20:36

So let's translate a logic that we just said into the code.

play20:40

So as soon as a number is found,

play20:42

we want to break the loop.

play20:44

So, our if condition here should be

play20:47

type of Jonas I,

play20:49

so the current element,

play20:51

if it's equal to a number,

play20:55

so now that's number then break.

play20:59

Now, okay.

play21:00

Let's see the result here.

play21:03

And indeed, that's exactly what we wanted.

play21:06

So after the first number is found

play21:09

which is this 46 here,

play21:11

nothing else is printed.

play21:13

So in this iteration where the number is found

play21:17

not even this line of code is printed anymore

play21:19

and then the loop is terminated completely.

play21:23

All right.

play21:24

Now this might not sound very practical,

play21:27

but believe me there are some important use cases

play21:30

for continue and break.

play21:32

It's just hard to create some small and isolated

play21:36

code examples to show you just how useful they can be.

play21:40

But anyway I wanted to let you know

play21:42

that continue and break exist.

play21:45

But the most important takeaway from this lecture,

play21:47

is definitely to understand,

play21:49

how we can loop through a race

play21:51

using this kind of logic here.

play21:54

Okay, so this one here is really important

play21:57

that you understand this snippet of code.

Rate This
★
★
★
★
★

5.0 / 5 (0 votes)

Besoin d'un résumé en anglais ?