Learn all about JavaScript loops 🤹 and how to write code that maximizes performance and readability, while avoiding the bad stuff 💩. https://fireship.io/snippets/javascript-loops-pro-tips/
2024-02-04T07:03:28.203Z
nova-2
2-general-nova
2024-01-09.29447
30089e05-99d1-4376-b32e-c263170674af
5e524aef-81dd-47d8-95e2-57640515867a
82a2d20036b2846ca90cd550c5f3a12f9d32577b440f73473c64c2ba3eb082cd
67875a7f-c9c4-48a0-aa55-5bdb8a91c34a
deprecated
Welcome to another episode of Code This Not That where we try to write the best code possible and avoid the bad stuff.
Today, we'll look at loops or iteration in JavaScript, which is a lot more interesting than you might We'll look at this from both a readability and performance perspective to figure out the best loop to write in your code.
If you're new here, like and subscribe, and I recommend following along with the source code on Fireship IO.
And if you wanna see more videos like this one, let me know in the comments.
When we talk about loops, we're actually talking about iteration which happens when we tell a computer to do something over and over again until we Tell It to Stop.
The best way to understand this is by looking at the traditional for loop.
First, we need to keep track of the number of iterations that we've made which usually starts 0.
Then we need a condition to stop the loop, and then we need to increment the counter each time an iteration is completed.
It's kind of like saying start here, Stop Here, and Do This after each completed loop.
This loop is very explicit because we can look at it and understand exactly what it's doing without making any assumptions.
But this code is kind of hard to digest.
And usually as programmers, we want to write as little code as possible and make that code understandable to other human beings.
Luckily, JavaScript provides 2 other ways to loop over things that are much more sugary and easier to understand for the average person.
The first one is the for of loop, and it's very similar to a 4 loop, except we use the of keyword and pass in the thing that we're iterating over.
Certain things in JavaScript are iterable, for example, arrays, maps, and strings.
So in this case, JavaScript will assume that we're iterating to the end of this array and will give us access to the elements in the array inside of the brackets.
So when just looping over an array, this is a lot less mental overhead than a traditional for loop.
But in order to really understand what's going on here, let's look at things at a lower level.
The array itself is iterable, and it implements an iterator function that allows it to be looped over.
We can actually override the default behavior of the for of loop by implementing our own iterator function.
So when we use the object in a for of loop, it's going to call this iterator function over and over again.
So what that means is we need to implement the same logic that we had in that traditional for loop.
So first, we set up an index at 0, then the array itself will be the this context inside of this function.
Now the actual spec itself requires us to return an object that has a next property, which is itself a function that returns an object that will tell the loop whether or not it's done and also provide the current value at this iteration.
So this isn't something that you would have to deal with on a daily basis, but it's good to know that JavaScript provides a way for you to make your own classes iterable or override the default iteration behavior on an existing object.
So I like to put emojis everywhere, so I'm gonna go ahead and add an emoji to every item in the loop.
So, obviously, it's not a very practical use case, but you can see we're just doing a regular for of loop here, but we're getting additional emojis added to the items in the loop.
We'll look at some more tricks we can do with for of in just a minute, but there's also one other way we can loop over items, and that's using a for each loop.
In this case, we're calling a method that exists on JavaScript arrays.
And we'll look at a bunch of these a little bit later, but, basically, it just allows us to pass a callback function that will be executed for every item in that array.
So we could go ahead and console log the value or we could even simplify this because console log itself is a function and we can just pass it in like this.
So it gives you the opportunity to write really concise functional code.
But when I did my original Code This, Not That video a few months ago, the main was not considering the performance implications of these different types of loops.
Those are absolutely valid points, so let's go ahead and look at the performance side by side.
I've created an array with a 1000000 items in it, and we'll go ahead and run our loops inside of a console timer.
First up is the traditional for loop, and you want to try to optimize your loop to do as little work in the loop itself as possible.
For example, you don't wanna call array dot length if you don't have to.
So in this case, we'll start by calling array dot length in the loop, and we get about 1.7 milliseconds.
If we just go ahead and pass in the number directly, we get slightly better performance at about 1.6 milliseconds.
Next up is the for of loop.
And when we run this, you can see we get about 11 to 12 milliseconds.
That's about 6 times longer, which is pretty crazy.
But when you think about all the extra work in that iterator function that we implemented earlier, then that performance loss makes sense.
But that shouldn't scare you away from using 4 of because if you're only looping over, say, a 1000 things, it's not going to matter.
It's really only a concern when every nanosecond counts.
And at that point, you might wanna consider something other than JavaScript.
Now back in our tests, we'll try 4 each, and we'll see that we get much better performance than 4 of at around 2 milliseconds or so.
But the interesting thing about these methods is that they can be chained together, and each one that you chain together is another iteration over the entire array.
So this time, we'll add map before we do our for each loop, and now you can see our performance is around 10 milliseconds.
So that's roughly 2 milliseconds from the for each loop and then another 8 seconds for map.
We can add another map in there and the performance will continue to decrease this time around 18 to 20 milliseconds.
So again, this probably won't matter if you have a small array, but something to keep in mind if performance is critical.
Now for the rest of the video, we're going to switch gears and just write some code that solves common problems that you'll encounter when running a loop.
The first one is how do you loop over an object?
Because an object is not iterable by default, although you could technically implement your own symbol iterator like we did earlier.
The easiest method is to just change your for of loop to a for in loop.
That will loop over all of the keys in the object, then you can simply use that key to access the value from the original object itself.
Another alternative would be to keep the for of loop in its original form, but this time use object values on the original object.
That will convert all of the values to an array, which of course is iterable.
And if you have an object that you know you need to loop over in different ways, I recommend converting it to a map.
A map shares a lot of similarities with a regular object, except it maintains the order of the keys in which they were inserted.
In other words, if you want to maintain a specific order of the key value pairs in the object, then you definitely wanna use a map and not a plain JavaScript object.
We can convert it by calling object entries on the original object inside of the map constructor, and we can loop over it by simply calling the values method on the map itself.
Now let's take a look at some of the very awesome methods that are available on the modern JavaScript array.
So here we have an array of faces, but you might notice one that doesn't quite fit.
It was meant to go in a completely different array, so let's go ahead and Create that array by filtering it out of the original.
We can do that by calling filter on the original array and keep in mind this is not removing it from the original but instead creating a new array with only that value.
So we can do this all in one line with array filter instead of setting up a 4 loop, which would at least take 5 lines of code.
Filter is pretty useful, but I think the most useful method is map.
It allows you to take the incoming elements in the array and transform them into something else.
But a lot of times when you're looping over an array, you're just testing that it contains something or maybe it doesn't contain something.
In our case, we're going to iterate over our faces array to see if it contains a certain unwanted emoji.
If any of the elements return true on this function, then the sum method on the array will return true.
And on a similar note, we can use the every method to ensure that every element in the array follows some pattern.
In our case, we're just making sure that it's a High Unicode character, which is where the emojis live.
Now let's say we had some more unwanted characters in this array, and we wanna see how bad the situation is by counting all of the unwanted characters.
The array reduce method allows us to loop over the array while accumulating a certain value.
And by accumulate, I just mean a value that changes after each iteration of the loop.
So the callback value contains that accumulated value as the first argument and then the current value in the loop as the second argument.
So all we're going to do is test that the emoji is the unwanted character, and if so, we'll add 1.
Otherwise, we'll add 0.
And when using reduce, you have the option to pass a second argument which is the starting value to accumulate from, which in our case would just be 0.
So now we know that we have 3 unwanted characters in this array.
So let's go ahead and sort it so all of the unwanted characters are at the end.
We have another array method just for that called array sort.
It allows you to pass in a compare function to sort the array based on whatever logic you want.
Once we have that sorted the way we want it, we can then call splice on the array to get rid of the elements that we don't need.
I'm gonna go ahead and wrap things up there.
Hopefully, this video showed you that there is always more than one way to solve a problem in JavaScript.
Make sure to grab the full source code from FireShip IO.
Thanks for watching, and I will talk to you soon.

Speaker 0: Welcome to another episode of Code This Not That where we try to write the best code possible and avoid the bad stuff. Today, we'll look at loops or iteration in JavaScript, which is a lot more interesting than you might We'll look at this from both a readability and performance perspective to figure out the best loop to write in your code. If you're new here, like and subscribe, and I recommend following along with the source code on Fireship IO. And if you wanna see more videos like this one, let me know in the comments. When we talk about loops, we're actually talking about iteration which happens when we tell a computer to do something over and over again until we Tell It to Stop.

The best way to understand this is by looking at the traditional for loop. First, we need to keep track of the number of iterations that we've made which usually starts 0. Then we need a condition to stop the loop, and then we need to increment the counter each time an iteration is completed. It's kind of like saying start here, Stop Here, and Do This after each completed loop. This loop is very explicit because we can look at it and understand exactly what it's doing without making any assumptions.

But this code is kind of hard to digest. And usually as programmers, we want to write as little code as possible and make that code understandable to other human beings. Luckily, JavaScript provides 2 other ways to loop over things that are much more sugary and easier to understand for the average person. The first one is the for of loop, and it's very similar to a 4 loop, except we use the of keyword and pass in the thing that we're iterating over. Certain things in JavaScript are iterable, for example, arrays, maps, and strings.

So in this case, JavaScript will assume that we're iterating to the end of this array and will give us access to the elements in the array inside of the brackets. So when just looping over an array, this is a lot less mental overhead than a traditional for loop. But in order to really understand what's going on here, let's look at things at a lower level. The array itself is iterable, and it implements an iterator function that allows it to be looped over. We can actually override the default behavior of the for of loop by implementing our own iterator function.

So when we use the object in a for of loop, it's going to call this iterator function over and over again. So what that means is we need to implement the same logic that we had in that traditional for loop. So first, we set up an index at 0, then the array itself will be the this context inside of this function. Now the actual spec itself requires us to return an object that has a next property, which is itself a function that returns an object that will tell the loop whether or not it's done and also provide the current value at this iteration. So this isn't something that you would have to deal with on a daily basis, but it's good to know that JavaScript provides a way for you to make your own classes iterable or override the default iteration behavior on an existing object.

So I like to put emojis everywhere, so I'm gonna go ahead and add an emoji to every item in the loop. So, obviously, it's not a very practical use case, but you can see we're just doing a regular for of loop here, but we're getting additional emojis added to the items in the loop. We'll look at some more tricks we can do with for of in just a minute, but there's also one other way we can loop over items, and that's using a for each loop. In this case, we're calling a method that exists on JavaScript arrays. And we'll look at a bunch of these a little bit later, but, basically, it just allows us to pass a callback function that will be executed for every item in that array.

So we could go ahead and console log the value or we could even simplify this because console log itself is a function and we can just pass it in like this. So it gives you the opportunity to write really concise functional code. But when I did my original Code This, Not That video a few months ago, the main was not considering the performance implications of these different types of loops. Those are absolutely valid points, so let's go ahead and look at the performance side by side. I've created an array with a 1000000 items in it, and we'll go ahead and run our loops inside of a console timer.

First up is the traditional for loop, and you want to try to optimize your loop to do as little work in the loop itself as possible. For example, you don't wanna call array dot length if you don't have to. So in this case, we'll start by calling array dot length in the loop, and we get about 1.7 milliseconds. If we just go ahead and pass in the number directly, we get slightly better performance at about 1.6 milliseconds. Next up is the for of loop.

And when we run this, you can see we get about 11 to 12 milliseconds. That's about 6 times longer, which is pretty crazy. But when you think about all the extra work in that iterator function that we implemented earlier, then that performance loss makes sense. But that shouldn't scare you away from using 4 of because if you're only looping over, say, a 1000 things, it's not going to matter. It's really only a concern when every nanosecond counts.

And at that point, you might wanna consider something other than JavaScript. Now back in our tests, we'll try 4 each, and we'll see that we get much better performance than 4 of at around 2 milliseconds or so. But the interesting thing about these methods is that they can be chained together, and each one that you chain together is another iteration over the entire array. So this time, we'll add map before we do our for each loop, and now you can see our performance is around 10 milliseconds. So that's roughly 2 milliseconds from the for each loop and then another 8 seconds for map.

We can add another map in there and the performance will continue to decrease this time around 18 to 20 milliseconds. So again, this probably won't matter if you have a small array, but something to keep in mind if performance is critical. Now for the rest of the video, we're going to switch gears and just write some code that solves common problems that you'll encounter when running a loop. The first one is how do you loop over an object? Because an object is not iterable by default, although you could technically implement your own symbol iterator like we did earlier.

The easiest method is to just change your for of loop to a for in loop. That will loop over all of the keys in the object, then you can simply use that key to access the value from the original object itself. Another alternative would be to keep the for of loop in its original form, but this time use object values on the original object. That will convert all of the values to an array, which of course is iterable. And if you have an object that you know you need to loop over in different ways, I recommend converting it to a map.

A map shares a lot of similarities with a regular object, except it maintains the order of the keys in which they were inserted. In other words, if you want to maintain a specific order of the key value pairs in the object, then you definitely wanna use a map and not a plain JavaScript object. We can convert it by calling object entries on the original object inside of the map constructor, and we can loop over it by simply calling the values method on the map itself. Now let's take a look at some of the very awesome methods that are available on the modern JavaScript array. So here we have an array of faces, but you might notice one that doesn't quite fit.

It was meant to go in a completely different array, so let's go ahead and Create that array by filtering it out of the original. We can do that by calling filter on the original array and keep in mind this is not removing it from the original but instead creating a new array with only that value. So we can do this all in one line with array filter instead of setting up a 4 loop, which would at least take 5 lines of code. Filter is pretty useful, but I think the most useful method is map. It allows you to take the incoming elements in the array and transform them into something else.

But a lot of times when you're looping over an array, you're just testing that it contains something or maybe it doesn't contain something. In our case, we're going to iterate over our faces array to see if it contains a certain unwanted emoji. If any of the elements return true on this function, then the sum method on the array will return true. And on a similar note, we can use the every method to ensure that every element in the array follows some pattern. In our case, we're just making sure that it's a High Unicode character, which is where the emojis live.

Now let's say we had some more unwanted characters in this array, and we wanna see how bad the situation is by counting all of the unwanted characters. The array reduce method allows us to loop over the array while accumulating a certain value. And by accumulate, I just mean a value that changes after each iteration of the loop. So the callback value contains that accumulated value as the first argument and then the current value in the loop as the second argument. So all we're going to do is test that the emoji is the unwanted character, and if so, we'll add 1.

Otherwise, we'll add 0. And when using reduce, you have the option to pass a second argument which is the starting value to accumulate from, which in our case would just be 0. So now we know that we have 3 unwanted characters in this array. So let's go ahead and sort it so all of the unwanted characters are at the end. We have another array method just for that called array sort.

It allows you to pass in a compare function to sort the array based on whatever logic you want. Once we have that sorted the way we want it, we can then call splice on the array to get rid of the elements that we don't need. I'm gonna go ahead and wrap things up there. Hopefully, this video showed you that there is always more than one way to solve a problem in JavaScript. Make sure to grab the full source code from FireShip IO.

Thanks for watching, and I will talk to you soon.
Welcome to another episode of Code This Not That where we try to write the best code possible and avoid the bad stuff. Today, we'll look at loops or iteration in JavaScript, which is a lot more interesting than you might We'll look at this from both a readability and performance perspective to figure out the best loop to write in your code. If you're new here, like and subscribe, and I recommend following along with the source code on Fireship IO. And if you wanna see more videos like this one, let me know in the comments. When we talk about loops, we're actually talking about iteration which happens when we tell a computer to do something over and over again until we Tell It to Stop.
programming
video gaming
The best way to understand this is by looking at the traditional for loop. First, we need to keep track of the number of iterations that we've made which usually starts 0.
Then we need a condition to stop the loop, and then we need to increment the counter each time an iteration is completed. It's kind of like saying start here, Stop Here, and Do This after each completed loop. This loop is very explicit because we can look at it and understand exactly what it's doing without making any assumptions. But this code is kind of hard to digest. And usually as programmers, we want to write as little code as possible and make that code understandable to other human beings. Luckily, JavaScript provides 2 other ways to loop over things that are much more sugary and easier to understand for the average person. The first one is the for of loop, and it's very similar to a 4 loop, except we use the of keyword and pass in the thing that we're iterating over.
programming
logic
operations
Certain things in JavaScript are iterable, for example, arrays, maps, and strings. So in this case, JavaScript will assume that we're iterating to the end of this array and will give us access to the elements in the array inside of the brackets. So when just looping over an array, this is a lot less mental overhead than a traditional for loop. But in order to really understand what's going on here, let's look at things at a lower level. The array itself is iterable, and it implements an iterator function that allows it to be looped over. We can actually override the default behavior of the for of loop by implementing our own iterator function. So when we use the object in a for of loop, it's going to call this iterator function over and over again. So what that means is we need to implement the same logic that we had in that traditional for loop. So first, we set up an index at 0, then the array itself will be the this context inside of this function. Now the actual spec itself requires us to return an object that has a next property, which is itself a function that returns an object that will tell the loop whether or not it's done and also provide the current value at this iteration. So this isn't something that you would have to deal with on a daily basis, but it's good to know that JavaScript provides a way for you to make your own classes iterable or override the default iteration behavior on an existing object. So I like to put emojis everywhere, so I'm gonna go ahead and add an emoji to every item in the loop. So, obviously, it's not a very practical use case, but you can see we're just doing a regular for of loop here, but we're getting additional emojis added to the items in the loop. We'll look at some more tricks we can do with for of in just a minute, but there's also one other way we can loop over items, and that's using a for each loop.
In this case, we're calling a method that exists on JavaScript arrays. And we'll look at a bunch of these a little bit later, but, basically, it just allows us to pass a callback function that will be executed for every item in that array. So we could go ahead and console log the value or we could even simplify this because console log itself is a function and we can just pass it in like this. So it gives you the opportunity to write really concise functional code. But when I did my original Code This, Not That video a few months ago, the main was not considering the performance implications of these different types of loops. Those are absolutely valid points, so let's go ahead and look at the performance side by side. I've created an array with a 1000000 items in it, and we'll go ahead and run our loops inside of a console timer. First up is the traditional for loop, and you want to try to optimize your loop to do as little work in the loop itself as possible.
programming
For example, you don't wanna call array dot length if you don't have to. So in this case, we'll start by calling array dot length in the loop, and we get about 1.7 milliseconds. If we just go ahead and pass in the number directly, we get slightly better performance at about 1.6 milliseconds. Next up is the for of loop. And when we run this, you can see we get about 11 to 12 milliseconds. That's about 6 times longer, which is pretty crazy. But when you think about all the extra work in that iterator function that we implemented earlier, then that performance loss makes sense. But that shouldn't scare you away from using 4 of because if you're only looping over, say, a 1000 things, it's not going to matter. It's really only a concern when every nanosecond counts. And at that point, you might wanna consider something other than JavaScript. Now back in our tests, we'll try 4 each, and we'll see that we get much better performance than 4 of at around 2 milliseconds or so. But the interesting thing about these methods is that they can be chained together, and each one that you chain together is another iteration over the entire array. So this time, we'll add map before we do our for each loop, and now you can see our performance is around 10 milliseconds. So that's roughly 2 milliseconds from the for each loop and then another 8 seconds for map. We can add another map in there and the performance will continue to decrease this time around 18 to 20 milliseconds. So again, this probably won't matter if you have a small array, but something to keep in mind if performance is critical. Now for the rest of the video, we're going to switch gears and just write some code that solves common problems that you'll encounter when running a loop. The first one is how do you loop over an object? Because an object is not iterable by default, although you could technically implement your own symbol iterator like we did earlier. The easiest method is to just change your for of loop to a for in loop. That will loop over all of the keys in the object, then you can simply use that key to access the value from the original object itself. Another alternative would be to keep the for of loop in its original form, but this time use object values on the original object. That will convert all of the values to an array, which of course is iterable. And if you have an object that you know you need to loop over in different ways, I recommend converting it to a map. A map shares a lot of similarities with a regular object, except it maintains the order of the keys in which they were inserted. In other words, if you want to maintain a specific order of the key value pairs in the object, then you definitely wanna use a map and not a plain JavaScript object. We can convert it by calling object entries on the original object inside of the map constructor, and we can loop over it by simply calling the values method on the map itself. Now let's take a look at some of the very awesome methods that are available on the modern JavaScript array. So here we have an array of faces, but you might notice one that doesn't quite fit. It was meant to go in a completely different array, so let's go ahead and Create that array by filtering it out of the original. We can do that by calling filter on the original array and keep in mind this is not removing it from the original but instead creating a new array with only that value. So we can do this all in one line with array filter instead of setting up a 4 loop, which would at least take 5 lines of code. Filter is pretty useful, but I think the most useful method is map. It allows you to take the incoming elements in the array and transform them into something else. But a lot of times when you're looping over an array, you're just testing that it contains something or maybe it doesn't contain something. In our case, we're going to iterate over our faces array to see if it contains a certain unwanted emoji. If any of the elements return true on this function, then the sum method on the array will return true. And on a similar note, we can use the every method to ensure that every element in the array follows some pattern. In our case, we're just making sure that it's a High Unicode character, which is where the emojis live. Now let's say we had some more unwanted characters in this array, and we wanna see how bad the situation is by counting all of the unwanted characters. The array reduce method allows us to loop over the array while accumulating a certain value. And by accumulate, I just mean a value that changes after each iteration of the loop. So the callback value contains that accumulated value as the first argument and then the current value in the loop as the second argument. So all we're going to do is test that the emoji is the unwanted character, and if so, we'll add 1. Otherwise, we'll add 0. And when using reduce, you have the option to pass a second argument which is the starting value to accumulate from, which in our case would just be 0. So now we know that we have 3 unwanted characters in this array. So let's go ahead and sort it so all of the unwanted characters are at the end. We have another array method just for that called array sort. It allows you to pass in a compare function to sort the array based on whatever logic you want. Once we have that sorted the way we want it, we can then call splice on the array to get rid of the elements that we don't need.
I'm gonna go ahead and wrap things up there. Hopefully, this video showed you that there is always more than one way to solve a problem in JavaScript. Make sure to grab the full source code from FireShip IO. Thanks for watching, and I will talk to you soon.
video gaming
streaming
Welcome to another episode of Code This Not That where we try to write the best code possible and avoid the bad stuff. Today, we'll look at loops or iteration in JavaScript, which is a lot more interesting than you might We'll look at this from both a readability and performance perspective to figure out the best loop to write in your code. If you're new here, like and subscribe, and I recommend following along with the source code on Fireship IO. And if you wanna see more videos like this one, let me know in the comments. When we talk about loops, we're actually talking about iteration which happens when we tell a computer to do something over and over again until we Tell It to Stop. The best way to understand this is by looking at the traditional for loop. First, we need to keep track of the number of iterations that we've made which usually starts 0. Then we need a condition to stop the loop, and then we need to increment the counter each time an iteration is completed. It's kind of like saying start here, Stop Here, and Do This after each completed loop. This loop is very explicit because we can look at it and understand exactly what it's doing without making any assumptions. But this code is kind of hard to digest. And usually as programmers, we want to write as little code as possible and make that code understandable to other human beings. Luckily, JavaScript provides 2 other ways to loop over things that are much more sugary and easier to understand for the average person. The first one is the for of loop, and it's very similar to a 4 loop, except we use the of keyword and pass in the thing that we're iterating over. Certain things in JavaScript are iterable, for example, arrays, maps, and strings. So in this case, JavaScript will assume that we're iterating to the end of this array and will give us access to the elements in the array inside of the brackets. So when just looping over an array, this is a lot less mental overhead than a traditional for loop. But in order to really understand what's going on here, let's look at things at a lower level. The array itself is iterable, and it implements an iterator function that allows it to be looped over. We can actually override the default behavior of the for of loop by implementing our own iterator function. So when we use the object in a for of loop, it's going to call this iterator function over and over again. So what that means is we need to implement the same logic that we had in that traditional for loop. So first, we set up an index at 0, then the array itself will be the this context inside of this function. Now the actual spec itself requires us to return an object that has a next property, which is itself a function that returns an object that will tell the loop whether or not it's done and also provide the current value at this iteration. So this isn't something that you would have to deal with on a daily basis, but it's good to know that JavaScript provides a way for you to make your own classes iterable or override the default iteration behavior on an existing object. So I like to put emojis everywhere, so I'm gonna go ahead and add an emoji to every item in the loop. So, obviously, it's not a very practical use case, but you can see we're just doing a regular for of loop here, but we're getting additional emojis added to the items in the loop. We'll look at some more tricks we can do with for of in just a minute, but there's also one other way we can loop over items, and that's using a for each loop. In this case, we're calling a method that exists on JavaScript arrays. And we'll look at a bunch of these a little bit later, but, basically, it just allows us to pass a callback function that will be executed for every item in that array. So we could go ahead and console log the value or we could even simplify this because console log itself is a function and we can just pass it in like this. So it gives you the opportunity to write really concise functional code. But when I did my original Code This, Not That video a few months ago, the main was not considering the performance implications of these different types of loops. Those are absolutely valid points, so let's go ahead and look at the performance side by side. I've created an array with a 1000000 items in it, and we'll go ahead and run our loops inside of a console timer. First up is the traditional for loop, and you want to try to optimize your loop to do as little work in the loop itself as possible. For example, you don't wanna call array dot length if you don't have to. So in this case, we'll start by calling array dot length in the loop, and we get about 1.7 milliseconds. If we just go ahead and pass in the number directly, we get slightly better performance at about 1.6 milliseconds. Next up is the for of loop. And when we run this, you can see we get about 11 to 12 milliseconds. That's about 6 times longer, which is pretty crazy. But when you think about all the extra work in that iterator function that we implemented earlier, then that performance loss makes sense. But that shouldn't scare you away from using 4 of because if you're only looping over, say, a 1000 things, it's not going to matter. It's really only a concern when every nanosecond counts. And at that point, you might wanna consider something other than JavaScript. Now back in our tests, we'll try 4 each, and we'll see that we get much better performance than 4 of at around 2 milliseconds or so. But the interesting thing about these methods is that they can be chained together, and each one that you chain together is another iteration over the entire array. So this time, we'll add map before we do our for each loop, and now you can see our performance is around 10 milliseconds. So that's roughly 2 milliseconds from the for each loop and then another 8 seconds for map. We can add another map in there and the performance will continue to decrease this time around 18 to 20 milliseconds. So again, this probably won't matter if you have a small array, but something to keep in mind if performance is critical. Now for the rest of the video, we're going to switch gears and just write some code that solves common problems that you'll encounter when running a loop. The first one is how do you loop over an object? Because an object is not iterable by default, although you could technically implement your own symbol iterator like we did earlier. The easiest method is to just change your for of loop to a for in loop. That will loop over all of the keys in the object, then you can simply use that key to access the value from the original object itself. Another alternative would be to keep the for of loop in its original form, but this time use object values on the original object. That will convert all of the values to an array, which of course is iterable. And if you have an object that you know you need to loop over in different ways, I recommend converting it to a map. A map shares a lot of similarities with a regular object, except it maintains the order of the keys in which they were inserted. In other words, if you want to maintain a specific order of the key value pairs in the object, then you definitely wanna use a map and not a plain JavaScript object. We can convert it by calling object entries on the original object inside of the map constructor, and we can loop over it by simply calling the values method on the map itself. Now let's take a look at some of the very awesome methods that are available on the modern JavaScript array. So here we have an array of faces, but you might notice one that doesn't quite fit. It was meant to go in a completely different array, so let's go ahead and Create that array by filtering it out of the original. We can do that by calling filter on the original array and keep in mind this is not removing it from the original but instead creating a new array with only that value. So we can do this all in one line with array filter instead of setting up a 4 loop, which would at least take 5 lines of code. Filter is pretty useful, but I think the most useful method is map. It allows you to take the incoming elements in the array and transform them into something else. But a lot of times when you're looping over an array, you're just testing that it contains something or maybe it doesn't contain something. In our case, we're going to iterate over our faces array to see if it contains a certain unwanted emoji. If any of the elements return true on this function, then the sum method on the array will return true. And on a similar note, we can use the every method to ensure that every element in the array follows some pattern. In our case, we're just making sure that it's a High Unicode character, which is where the emojis live. Now let's say we had some more unwanted characters in this array, and we wanna see how bad the situation is by counting all of the unwanted characters. The array reduce method allows us to loop over the array while accumulating a certain value. And by accumulate, I just mean a value that changes after each iteration of the loop. So the callback value contains that accumulated value as the first argument and then the current value in the loop as the second argument. So all we're going to do is test that the emoji is the unwanted character, and if so, we'll add 1. Otherwise, we'll add 0. And when using reduce, you have the option to pass a second argument which is the starting value to accumulate from, which in our case would just be 0. So now we know that we have 3 unwanted characters in this array. So let's go ahead and sort it so all of the unwanted characters are at the end. We have another array method just for that called array sort. It allows you to pass in a compare function to sort the array based on whatever logic you want. Once we have that sorted the way we want it, we can then call splice on the array to get rid of the elements that we don't need. I'm gonna go ahead and wrap things up there. Hopefully, this video showed you that there is always more than one way to solve a problem in JavaScript. Make sure to grab the full source code from FireShip IO. Thanks for watching, and I will talk to you soon.
Welcome
welcome
to
to
another
another
episode
episode
of
of
Code
code
This
this
Not
not
That
that
where
where
we
we
try
try
to
to
write
write
the
the
best
best
code
code
possible
possible
and
and
avoid
avoid
the
the
bad
bad
stuff.
stuff
Today,
today
we'll
we'll
look
look
at
at
loops
loops
or
or
iteration
iteration
in
in
JavaScript,
javascript
which
which
is
is
a
a
lot
lot
more
more
interesting
interesting
than
than
you
you
might
might
We'll
we'll
look
look
at
at
this
this
from
from
both
both
a
a
readability
readability
and
and
performance
performance
perspective
perspective
to
to
figure
figure
out
out
the
the
best
best
loop
loop
to
to
write
write
in
in
your
your
code.
code
If
if
you're
you're
new
new
here,
here
like
like
and
and
subscribe,
subscribe
and
and
I
i
recommend
recommend
following
following
along
along
with
with
the
the
source
source
code
code
on
on
Fireship
fireship
IO.
io
And
and
if
if
you
you
wanna
wanna
see
see
more
more
videos
videos
like
like
this
this
one,
one
let
let
me
me
know
know
in
in
the
the
comments.
comments
When
when
we
we
talk
talk
about
about
loops,
loops
we're
we're
actually
actually
talking
talking
about
about
iteration
iteration
which
which
happens
happens
when
when
we
we
tell
tell
a
a
computer
computer
to
to
do
do
something
something
over
over
and
and
over
over
again
again
until
until
we
we
Tell
tell
It
it
to
to
Stop.
stop
The
the
best
best
way
way
to
to
understand
understand
this
this
is
is
by
by
looking
looking
at
at
the
the
traditional
traditional
for
for
loop.
loop
First,
first
we
we
need
need
to
to
keep
keep
track
track
of
of
the
the
number
number
of
of
iterations
iterations
that
that
we've
we've
made
made
which
which
usually
usually
starts
starts
0.
0
Then
then
we
we
need
need
a
a
condition
condition
to
to
stop
stop
the
the
loop,
loop
and
and
then
then
we
we
need
need
to
to
increment
increment
the
the
counter
counter
each
each
time
time
an
an
iteration
iteration
is
is
completed.
completed
It's
it's
kind
kind
of
of
like
like
saying
saying
start
start
here,
here
Stop
stop
Here,
here
and
and
Do
do
This
this
after
after
each
each
completed
completed
loop.
loop
This
this
loop
loop
is
is
very
very
explicit
explicit
because
because
we
we
can
can
look
look
at
at
it
it
and
and
understand
understand
exactly
exactly
what
what
it's
it's
doing
doing
without
without
making
making
any
any
assumptions.
assumptions
But
but
this
this
code
code
is
is
kind
kind
of
of
hard
hard
to
to
digest.
digest
And
and
usually
usually
as
as
programmers,
programmers
we
we
want
want
to
to
write
write
as
as
little
little
code
code
as
as
possible
possible
and
and
make
make
that
that
code
code
understandable
understandable
to
to
other
other
human
human
beings.
beings
Luckily,
luckily
JavaScript
javascript
provides
provides
2
2
other
other
ways
ways
to
to
loop
loop
over
over
things
things
that
that
are
are
much
much
more
more
sugary
sugary
and
and
easier
easier
to
to
understand
understand
for
for
the
the
average
average
person.
person
The
the
first
first
one
one
is
is
the
the
for
for
of
of
loop,
loop
and
and
it's
it's
very
very
similar
similar
to
to
a
a
4
4
loop,
loop
except
except
we
we
use
use
the
the
of
of
keyword
keyword
and
and
pass
pass
in
in
the
the
thing
thing
that
that
we're
we're
iterating
iterating
over.
over
Certain
certain
things
things
in
in
JavaScript
javascript
are
are
iterable,
iterable
for
for
example,
example
arrays,
arrays
maps,
maps
and
and
strings.
strings
So
so
in
in
this
this
case,
case
JavaScript
javascript
will
will
assume
assume
that
that
we're
we're
iterating
iterating
to
to
the
the
end
end
of
of
this
this
array
array
and
and
will
will
give
give
us
us
access
access
to
to
the
the
elements
elements
in
in
the
the
array
array
inside
inside
of
of
the
the
brackets.
brackets
So
so
when
when
just
just
looping
looping
over
over
an
an
array,
array
this
this
is
is
a
a
lot
lot
less
less
mental
mental
overhead
overhead
than
than
a
a
traditional
traditional
for
for
loop.
loop
But
but
in
in
order
order
to
to
really
really
understand
understand
what's
what's
going
going
on
on
here,
here
let's
let's
look
look
at
at
things
things
at
at
a
a
lower
lower
level.
level
The
the
array
array
itself
itself
is
is
iterable,
iterable
and
and
it
it
implements
implements
an
an
iterator
iterator
function
function
that
that
allows
allows
it
it
to
to
be
be
looped
looped
over.
over
We
we
can
can
actually
actually
override
override
the
the
default
default
behavior
behavior
of
of
the
the
for
for
of
of
loop
loop
by
by
implementing
implementing
our
our
own
own
iterator
iterator
function.
function
So
so
when
when
we
we
use
use
the
the
object
object
in
in
a
a
for
for
of
of
loop,
loop
it's
it's
going
going
to
to
call
call
this
this
iterator
iterator
function
function
over
over
and
and
over
over
again.
again
So
so
what
what
that
that
means
means
is
is
we
we
need
need
to
to
implement
implement
the
the
same
same
logic
logic
that
that
we
we
had
had
in
in
that
that
traditional
traditional
for
for
loop.
loop
So
so
first,
first
we
we
set
set
up
up
an
an
index
index
at
at
0,
0
then
then
the
the
array
array
itself
itself
will
will
be
be
the
the
this
this
context
context
inside
inside
of
of
this
this
function.
function
Now
now
the
the
actual
actual
spec
spec
itself
itself
requires
requires
us
us
to
to
return
return
an
an
object
object
that
that
has
has
a
a
next
next
property,
property
which
which
is
is
itself
itself
a
a
function
function
that
that
returns
returns
an
an
object
object
that
that
will
will
tell
tell
the
the
loop
loop
whether
whether
or
or
not
not
it's
it's
done
done
and
and
also
also
provide
provide
the
the
current
current
value
value
at
at
this
this
iteration.
iteration
So
so
this
this
isn't
isn't
something
something
that
that
you
you
would
would
have
have
to
to
deal
deal
with
with
on
on
a
a
daily
daily
basis,
basis
but
but
it's
it's
good
good
to
to
know
know
that
that
JavaScript
javascript
provides
provides
a
a
way
way
for
for
you
you
to
to
make
make
your
your
own
own
classes
classes
iterable
iterable
or
or
override
override
the
the
default
default
iteration
iteration
behavior
behavior
on
on
an
an
existing
existing
object.
object
So
so
I
i
like
like
to
to
put
put
emojis
emojis
everywhere,
everywhere
so
so
I'm
i'm
gonna
gonna
go
go
ahead
ahead
and
and
add
add
an
an
emoji
emoji
to
to
every
every
item
item
in
in
the
the
loop.
loop
So,
so
obviously,
obviously
it's
it's
not
not
a
a
very
very
practical
practical
use
use
case,
case
but
but
you
you
can
can
see
see
we're
we're
just
just
doing
doing
a
a
regular
regular
for
for
of
of
loop
loop
here,
here
but
but
we're
we're
getting
getting
additional
additional
emojis
emojis
added
added
to
to
the
the
items
items
in
in
the
the
loop.
loop
We'll
we'll
look
look
at
at
some
some
more
more
tricks
tricks
we
we
can
can
do
do
with
with
for
for
of
of
in
in
just
just
a
a
minute,
minute
but
but
there's
there's
also
also
one
one
other
other
way
way
we
we
can
can
loop
loop
over
over
items,
items
and
and
that's
that's
using
using
a
a
for
for
each
each
loop.
loop
In
in
this
this
case,
case
we're
we're
calling
calling
a
a
method
method
that
that
exists
exists
on
on
JavaScript
javascript
arrays.
arrays
And
and
we'll
we'll
look
look
at
at
a
a
bunch
bunch
of
of
these
these
a
a
little
little
bit
bit
later,
later
but,
but
basically,
basically
it
it
just
just
allows
allows
us
us
to
to
pass
pass
a
a
callback
callback
function
function
that
that
will
will
be
be
executed
executed
for
for
every
every
item
item
in
in
that
that
array.
array
So
so
we
we
could
could
go
go
ahead
ahead
and
and
console
console
log
log
the
the
value
value
or
or
we
we
could
could
even
even
simplify
simplify
this
this
because
because
console
console
log
log
itself
itself
is
is
a
a
function
function
and
and
we
we
can
can
just
just
pass
pass
it
it
in
in
like
like
this.
this
So
so
it
it
gives
gives
you
you
the
the
opportunity
opportunity
to
to
write
write
really
really
concise
concise
functional
functional
code.
code
But
but
when
when
I
i
did
did
my
my
original
original
Code
code
This,
this
Not
not
That
that
video
video
a
a
few
few
months
months
ago,
ago
the
the
main
main
was
was
not
not
considering
considering
the
the
performance
performance
implications
implications
of
of
these
these
different
different
types
types
of
of
loops.
loops
Those
those
are
are
absolutely
absolutely
valid
valid
points,
points
so
so
let's
let's
go
go
ahead
ahead
and
and
look
look
at
at
the
the
performance
performance
side
side
by
by
side.
side
I've
i've
created
created
an
an
array
array
with
with
a
a
1000000
1000000
items
items
in
in
it,
it
and
and
we'll
we'll
go
go
ahead
ahead
and
and
run
run
our
our
loops
loops
inside
inside
of
of
a
a
console
console
timer.
timer
First
first
up
up
is
is
the
the
traditional
traditional
for
for
loop,
loop
and
and
you
you
want
want
to
to
try
try
to
to
optimize
optimize
your
your
loop
loop
to
to
do
do
as
as
little
little
work
work
in
in
the
the
loop
loop
itself
itself
as
as
possible.
possible
For
for
example,
example
you
you
don't
don't
wanna
wanna
call
call
array
array
dot
dot
length
length
if
if
you
you
don't
don't
have
have
to.
to
So
so
in
in
this
this
case,
case
we'll
we'll
start
start
by
by
calling
calling
array
array
dot
dot
length
length
in
in
the
the
loop,
loop
and
and
we
we
get
get
about
about
1.7
1.7
milliseconds.
milliseconds
If
if
we
we
just
just
go
go
ahead
ahead
and
and
pass
pass
in
in
the
the
number
number
directly,
directly
we
we
get
get
slightly
slightly
better
better
performance
performance
at
at
about
about
1.6
1.6
milliseconds.
milliseconds
Next
next
up
up
is
is
the
the
for
for
of
of
loop.
loop
And
and
when
when
we
we
run
run
this,
this
you
you
can
can
see
see
we
we
get
get
about
about
11
11
to
to
12
12
milliseconds.
milliseconds
That's
that's
about
about
6
6
times
times
longer,
longer
which
which
is
is
pretty
pretty
crazy.
crazy
But
but
when
when
you
you
think
think
about
about
all
all
the
the
extra
extra
work
work
in
in
that
that
iterator
iterator
function
function
that
that
we
we
implemented
implemented
earlier,
earlier
then
then
that
that
performance
performance
loss
loss
makes
makes
sense.
sense
But
but
that
that
shouldn't
shouldn't
scare
scare
you
you
away
away
from
from
using
using
4
4
of
of
because
because
if
if
you're
you're
only
only
looping
looping
over,
over
say,
say
a
a
1000
1000
things,
things
it's
it's
not
not
going
going
to
to
matter.
matter
It's
it's
really
really
only
only
a
a
concern
concern
when
when
every
every
nanosecond
nanosecond
counts.
counts
And
and
at
at
that
that
point,
point
you
you
might
might
wanna
wanna
consider
consider
something
something
other
other
than
than
JavaScript.
javascript
Now
now
back
back
in
in
our
our
tests,
tests
we'll
we'll
try
try
4
4
each,
each
and
and
we'll
we'll
see
see
that
that
we
we
get
get
much
much
better
better
performance
performance
than
than
4
4
of
of
at
at
around
around
2
2
milliseconds
milliseconds
or
or
so.
so
But
but
the
the
interesting
interesting
thing
thing
about
about
these
these
methods
methods
is
is
that
that
they
they
can
can
be
be
chained
chained
together,
together
and
and
each
each
one
one
that
that
you
you
chain
chain
together
together
is
is
another
another
iteration
iteration
over
over
the
the
entire
entire
array.
array
So
so
this
this
time,
time
we'll
we'll
add
add
map
map
before
before
we
we
do
do
our
our
for
for
each
each
loop,
loop
and
and
now
now
you
you
can
can
see
see
our
our
performance
performance
is
is
around
around
10
10
milliseconds.
milliseconds
So
so
that's
that's
roughly
roughly
2
2
milliseconds
milliseconds
from
from
the
the
for
for
each
each
loop
loop
and
and
then
then
another
another
8
8
seconds
seconds
for
for
map.
map
We
we
can
can
add
add
another
another
map
map
in
in
there
there
and
and
the
the
performance
performance
will
will
continue
continue
to
to
decrease
decrease
this
this
time
time
around
around
18
18
to
to
20
20
milliseconds.
milliseconds
So
so
again,
again
this
this
probably
probably
won't
won't
matter
matter
if
if
you
you
have
have
a
a
small
small
array,
array
but
but
something
something
to
to
keep
keep
in
in
mind
mind
if
if
performance
performance
is
is
critical.
critical
Now
now
for
for
the
the
rest
rest
of
of
the
the
video,
video
we're
we're
going
going
to
to
switch
switch
gears
gears
and
and
just
just
write
write
some
some
code
code
that
that
solves
solves
common
common
problems
problems
that
that
you'll
you'll
encounter
encounter
when
when
running
running
a
a
loop.
loop
The
the
first
first
one
one
is
is
how
how
do
do
you
you
loop
loop
over
over
an
an
object?
object
Because
because
an
an
object
object
is
is
not
not
iterable
iterable
by
by
default,
default
although
although
you
you
could
could
technically
technically
implement
implement
your
your
own
own
symbol
symbol
iterator
iterator
like
like
we
we
did
did
earlier.
earlier
The
the
easiest
easiest
method
method
is
is
to
to
just
just
change
change
your
your
for
for
of
of
loop
loop
to
to
a
a
for
for
in
in
loop.
loop
That
that
will
will
loop
loop
over
over
all
all
of
of
the
the
keys
keys
in
in
the
the
object,
object
then
then
you
you
can
can
simply
simply
use
use
that
that
key
key
to
to
access
access
the
the
value
value
from
from
the
the
original
original
object
object
itself.
itself
Another
another
alternative
alternative
would
would
be
be
to
to
keep
keep
the
the
for
for
of
of
loop
loop
in
in
its
its
original
original
form,
form
but
but
this
this
time
time
use
use
object
object
values
values
on
on
the
the
original
original
object.
object
That
that
will
will
convert
convert
all
all
of
of
the
the
values
values
to
to
an
an
array,
array
which
which
of
of
course
course
is
is
iterable.
iterable
And
and
if
if
you
you
have
have
an
an
object
object
that
that
you
you
know
know
you
you
need
need
to
to
loop
loop
over
over
in
in
different
different
ways,
ways
I
i
recommend
recommend
converting
converting
it
it
to
to
a
a
map.
map
A
a
map
map
shares
shares
a
a
lot
lot
of
of
similarities
similarities
with
with
a
a
regular
regular
object,
object
except
except
it
it
maintains
maintains
the
the
order
order
of
of
the
the
keys
keys
in
in
which
which
they
they
were
were
inserted.
inserted
In
in
other
other
words,
words
if
if
you
you
want
want
to
to
maintain
maintain
a
a
specific
specific
order
order
of
of
the
the
key
key
value
value
pairs
pairs
in
in
the
the
object,
object
then
then
you
you
definitely
definitely
wanna
wanna
use
use
a
a
map
map
and
and
not
not
a
a
plain
plain
JavaScript
javascript
object.
object
We
we
can
can
convert
convert
it
it
by
by
calling
calling
object
object
entries
entries
on
on
the
the
original
original
object
object
inside
inside
of
of
the
the
map
map
constructor,
constructor
and
and
we
we
can
can
loop
loop
over
over
it
it
by
by
simply
simply
calling
calling
the
the
values
values
method
method
on
on
the
the
map
map
itself.
itself
Now
now
let's
let's
take
take
a
a
look
look
at
at
some
some
of
of
the
the
very
very
awesome
awesome
methods
methods
that
that
are
are
available
available
on
on
the
the
modern
modern
JavaScript
javascript
array.
array
So
so
here
here
we
we
have
have
an
an
array
array
of
of
faces,
faces
but
but
you
you
might
might
notice
notice
one
one
that
that
doesn't
doesn't
quite
quite
fit.
fit
It
it
was
was
meant
meant
to
to
go
go
in
in
a
a
completely
completely
different
different
array,
array
so
so
let's
let's
go
go
ahead
ahead
and
and
Create
create
that
that
array
array
by
by
filtering
filtering
it
it
out
out
of
of
the
the
original.
original
We
we
can
can
do
do
that
that
by
by
calling
calling
filter
filter
on
on
the
the
original
original
array
array
and
and
keep
keep
in
in
mind
mind
this
this
is
is
not
not
removing
removing
it
it
from
from
the
the
original
original
but
but
instead
instead
creating
creating
a
a
new
new
array
array
with
with
only
only
that
that
value.
value
So
so
we
we
can
can
do
do
this
this
all
all
in
in
one
one
line
line
with
with
array
array
filter
filter
instead
instead
of
of
setting
setting
up
up
a
a
4
4
loop,
loop
which
which
would
would
at
at
least
least
take
take
5
5
lines
lines
of
of
code.
code
Filter
filter
is
is
pretty
pretty
useful,
useful
but
but
I
i
think
think
the
the
most
most
useful
useful
method
method
is
is
map.
map
It
it
allows
allows
you
you
to
to
take
take
the
the
incoming
incoming
elements
elements
in
in
the
the
array
array
and
and
transform
transform
them
them
into
into
something
something
else.
else
But
but
a
a
lot
lot
of
of
times
times
when
when
you're
you're
looping
looping
over
over
an
an
array,
array
you're
you're
just
just
testing
testing
that
that
it
it
contains
contains
something
something
or
or
maybe
maybe
it
it
doesn't
doesn't
contain
contain
something.
something
In
in
our
our
case,
case
we're
we're
going
going
to
to
iterate
iterate
over
over
our
our
faces
faces
array
array
to
to
see
see
if
if
it
it
contains
contains
a
a
certain
certain
unwanted
unwanted
emoji.
emoji
If
if
any
any
of
of
the
the
elements
elements
return
return
true
true
on
on
this
this
function,
function
then
then
the
the
sum
sum
method
method
on
on
the
the
array
array
will
will
return
return
true.
true
And
and
on
on
a
a
similar
similar
note,
note
we
we
can
can
use
use
the
the
every
every
method
method
to
to
ensure
ensure
that
that
every
every
element
element
in
in
the
the
array
array
follows
follows
some
some
pattern.
pattern
In
in
our
our
case,
case
we're
we're
just
just
making
making
sure
sure
that
that
it's
it's
a
a
High
high
Unicode
unicode
character,
character
which
which
is
is
where
where
the
the
emojis
emojis
live.
live
Now
now
let's
let's
say
say
we
we
had
had
some
some
more
more
unwanted
unwanted
characters
characters
in
in
this
this
array,
array
and
and
we
we
wanna
wanna
see
see
how
how
bad
bad
the
the
situation
situation
is
is
by
by
counting
counting
all
all
of
of
the
the
unwanted
unwanted
characters.
characters
The
the
array
array
reduce
reduce
method
method
allows
allows
us
us
to
to
loop
loop
over
over
the
the
array
array
while
while
accumulating
accumulating
a
a
certain
certain
value.
value
And
and
by
by
accumulate,
accumulate
I
i
just
just
mean
mean
a
a
value
value
that
that
changes
changes
after
after
each
each
iteration
iteration
of
of
the
the
loop.
loop
So
so
the
the
callback
callback
value
value
contains
contains
that
that
accumulated
accumulated
value
value
as
as
the
the
first
first
argument
argument
and
and
then
then
the
the
current
current
value
value
in
in
the
the
loop
loop
as
as
the
the
second
second
argument.
argument
So
so
all
all
we're
we're
going
going
to
to
do
do
is
is
test
test
that
that
the
the
emoji
emoji
is
is
the
the
unwanted
unwanted
character,
character
and
and
if
if
so,
so
we'll
we'll
add
add
1.
1
Otherwise,
otherwise
we'll
we'll
add
add
0.
0
And
and
when
when
using
using
reduce,
reduce
you
you
have
have
the
the
option
option
to
to
pass
pass
a
a
second
second
argument
argument
which
which
is
is
the
the
starting
starting
value
value
to
to
accumulate
accumulate
from,
from
which
which
in
in
our
our
case
case
would
would
just
just
be
be
0.
0
So
so
now
now
we
we
know
know
that
that
we
we
have
have
3
3
unwanted
unwanted
characters
characters
in
in
this
this
array.
array
So
so
let's
let's
go
go
ahead
ahead
and
and
sort
sort
it
it
so
so
all
all
of
of
the
the
unwanted
unwanted
characters
characters
are
are
at
at
the
the
end.
end
We
we
have
have
another
another
array
array
method
method
just
just
for
for
that
that
called
called
array
array
sort.
sort
It
it
allows
allows
you
you
to
to
pass
pass
in
in
a
a
compare
compare
function
function
to
to
sort
sort
the
the
array
array
based
based
on
on
whatever
whatever
logic
logic
you
you
want.
want
Once
once
we
we
have
have
that
that
sorted
sorted
the
the
way
way
we
we
want
want
it,
it
we
we
can
can
then
then
call
call
splice
splice
on
on
the
the
array
array
to
to
get
get
rid
rid
of
of
the
the
elements
elements
that
that
we
we
don't
don't
need.
need
I'm
i'm
gonna
gonna
go
go
ahead
ahead
and
and
wrap
wrap
things
things
up
up
there.
there
Hopefully,
hopefully
this
this
video
video
showed
showed
you
you
that
that
there
there
is
is
always
always
more
more
than
than
one
one
way
way
to
to
solve
solve
a
a
problem
problem
in
in
JavaScript.
javascript
Make
make
sure
sure
to
to
grab
grab
the
the
full
full
source
source
code
code
from
from
FireShip
fireship
IO.
io
Thanks
thanks
for
for
watching,
watching
and
and
I
i
will
will
talk
talk
to
to
you
you
soon.
soon
success
The loop in JavaScript is explicit and can be used to create new classes or override default iteration behavior. The performance side is looked at by running a loop in a console timer, with the loss of performance loss of about 1.6 milliseconds. The speaker explains the use of a method called "map" in JavaScript to prevent unwanted objects from being encountered, and other methods available in the JavaScript array, including "by default" and "way to" methods. They stress the importance of testing accuracy of results and provide examples of how these methods can be used.
JavaScript Loops - Code This, Not That
Welcome to another episode of Code This Not That where we try to write the best code possible and avoid the bad stuff. Today, we'll look at loops or iteration in JavaScript, which is a lot more interesting than you might We'll look at this from both a readability and performance perspective to figure out the best loop to write in your code. If you're new here, like and subscribe, and I recommend following along with the source code on Fireship IO. And if you wanna see more videos like this one, let me know in the comments. When we talk about loops, we're actually talking about iteration which happens when we tell a computer to do something over and over again until we Tell It to Stop. The best way to understand this is by looking at the traditional for loop. First, we need to keep track of the number of iterations that we've made which usually starts 0. Then we need a condition to stop the loop, and then we need to increment the counter each time an iteration is completed. It's kind of like saying start here, Stop Here, and Do This after each completed loop. This loop is very explicit because we can look at it and understand exactly what it's doing without making any assumptions. But this code is kind of hard to digest. And usually as programmers, we want to write as little code as possible and make that code understandable to other human beings. Luckily, JavaScript provides 2 other ways to loop over things that are much more sugary and easier to understand for the average person. The first one is the for of loop, and it's very similar to a 4 loop, except we use the of keyword and pass in the thing that we're iterating over. Certain things in JavaScript are iterable, for example, arrays, maps, and strings. So in this case, JavaScript will assume that we're iterating to the end of this array and will give us access to the elements in the array inside of the brackets. So when just looping over an array, this is a lot less mental overhead than a traditional for loop. But in order to really understand what's going on here, let's look at things at a lower level. The array itself is iterable, and it implements an iterator function that allows it to be looped over. We can actually override the default behavior of the for of loop by implementing our own iterator function. So when we use the object in a for of loop, it's going to call this iterator function over and over again. So what that means is we need to implement the same logic that we had in that traditional for loop. So first, we set up an index at 0, then the array itself will be the this context inside of this function. Now the actual spec itself requires us to return an object that has a next property, which is itself a function that returns an object that will tell the loop whether or not it's done and also provide the current value at this iteration. So this isn't something that you would have to deal with on a daily basis, but it's good to know that JavaScript provides a way for you to make your own classes iterable or override the default iteration behavior on an existing object. So I like to put emojis everywhere, so I'm gonna go ahead and add an emoji to every item in the loop. So, obviously, it's not a very practical use case, but you can see we're just doing a regular for of loop here, but we're getting additional emojis added to the items in the loop. We'll look at some more tricks we can do with for of in just a minute, but there's also one other way we can loop over items, and that's using a for each loop. In this case, we're calling a method that exists on JavaScript arrays. And we'll look at a bunch of these a little bit later, but, basically, it just allows us to pass a callback function that will be executed for every item in that array. So we could go ahead and console log the value or we could even simplify this because console log itself is a function and we can just pass it in like this. So it gives you the opportunity to write really concise functional code. But when I did my original Code This, Not That video a few months ago, the main was not considering the performance implications of these different types of loops. Those are absolutely valid points, so let's go ahead and look at the performance side by side. I've created an array with a 1000000 items in it, and we'll go ahead and run our loops inside of a console timer. First up is the traditional for loop, and you want to try to optimize your loop to do as little work in the loop itself as possible. For example, you don't wanna call array dot length if you don't have to. So in this case, we'll start by calling array dot length in the loop, and we get about 1.7 milliseconds. If we just go ahead and pass in the number directly, we get slightly better performance at about 1.6 milliseconds. Next up is the for of loop. And when we run this, you can see we get about 11 to 12 milliseconds. That's about 6 times longer, which is pretty crazy. But when you think about all the extra work in that iterator function that we implemented earlier, then that performance loss makes sense. But that shouldn't scare you away from using 4 of because if you're only looping over, say, a 1000 things, it's not going to matter. It's really only a concern when every nanosecond counts. And at that point, you might wanna consider something other than JavaScript. Now back in our tests, we'll try 4 each, and we'll see that we get much better performance than 4 of at around 2 milliseconds or so. But the interesting thing about these methods is that they can be chained together, and each one that you chain together is another iteration over the entire array. So this time, we'll add map before we do our for each loop, and now you can see our performance is around 10 milliseconds. So that's roughly 2 milliseconds from the for each loop and then another 8 seconds for map. We can add another map in there and the performance will continue to decrease this time around 18 to 20 milliseconds. So again, this probably won't matter if you have a small array, but something to keep in mind if performance is critical. Now for the rest of the video, we're going to switch gears and just write some code that solves common problems that you'll encounter when running a loop. The first one is how do you loop over an object? Because an object is not iterable by default, although you could technically implement your own symbol iterator like we did earlier. The easiest method is to just change your for of loop to a for in loop. That will loop over all of the keys in the object, then you can simply use that key to access the value from the original object itself. Another alternative would be to keep the for of loop in its original form, but this time use object values on the original object. That will convert all of the values to an array, which of course is iterable. And if you have an object that you know you need to loop over in different ways, I recommend converting it to a map. A map shares a lot of similarities with a regular object, except it maintains the order of the keys in which they were inserted. In other words, if you want to maintain a specific order of the key value pairs in the object, then you definitely wanna use a map and not a plain JavaScript object. We can convert it by calling object entries on the original object inside of the map constructor, and we can loop over it by simply calling the values method on the map itself. Now let's take a look at some of the very awesome methods that are available on the modern JavaScript array. So here we have an array of faces, but you might notice one that doesn't quite fit. It was meant to go in a completely different array, so let's go ahead and Create that array by filtering it out of the original. We can do that by calling filter on the original array and keep in mind this is not removing it from the original but instead creating a new array with only that value. So we can do this all in one line with array filter instead of setting up a 4 loop, which would at least take 5 lines of code. Filter is pretty useful, but I think the most useful method is map. It allows you to take the incoming elements in the array and transform them into something else. But a lot of times when you're looping over an array, you're just testing that it contains something or maybe it doesn't contain something. In our case, we're going to iterate over our faces array to see if it contains a certain unwanted emoji. If any of the elements return true on this function, then the sum method on the array will return true. And on a similar note, we can use the every method to ensure that every element in the array follows some pattern. In our case, we're just making sure that it's a High Unicode character, which is where the emojis live. Now let's say we had some more unwanted characters in this array, and we wanna see how bad the situation is by counting all of the unwanted characters. The array reduce method allows us to loop over the array while accumulating a certain value. And by accumulate, I just mean a value that changes after each iteration of the loop. So the callback value contains that accumulated value as the first argument and then the current value in the loop as the second argument. So all we're going to do is test that the emoji is the unwanted character, and if so, we'll add 1. Otherwise, we'll add 0. And when using reduce, you have the option to pass a second argument which is the starting value to accumulate from, which in our case would just be 0. So now we know that we have 3 unwanted characters in this array. So let's go ahead and sort it so all of the unwanted characters are at the end. We have another array method just for that called array sort. It allows you to pass in a compare function to sort the array based on whatever logic you want. Once we have that sorted the way we want it, we can then call splice on the array to get rid of the elements that we don't need. I'm gonna go ahead and wrap things up there. Hopefully, this video showed you that there is always more than one way to solve a problem in JavaScript. Make sure to grab the full source code from FireShip IO. Thanks for watching, and I will talk to you soon.
The loop in JavaScript is explicit and can be used to create new classes or override default iteration behavior. The performance side is looked at by running a loop in a console timer, with the loss of performance loss of about 1.6 milliseconds. The speaker explains the use of a method called "map" in JavaScript to prevent unwanted objects from being encountered, and other methods available in the JavaScript array, including "by default" and "way to" methods. They stress the importance of testing accuracy of results and provide examples of how these methods can be used.