JavaScript Loops - Code This, Not That

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] 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 and JavaScript which is a lot more interesting than you might think 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 fire ship IO and if you want to 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 at zero 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 two 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 for loop except we use the of keyword and pass and 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 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 that 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 well look at some more tricks we can do with four 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 that main criticism 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 million 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 want to 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 thousand things it's not going to matter it's really only a concern when every nanosecond counts and at that point you might want to consider something other than javascript now back in our tests will try for each and we'll see that we get much better performance than for of at around two milliseconds or so but the interesting thing about these methods is that they can be chained together and each one that you've chained together is a another iteration over the entire array so this time we'll add nap before we do our for each loop and now you can see our performances 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 want to use a map and not a plain JavaScript object we can convert it by a 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 array 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 for loop which would at least take five 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 want to 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 one otherwise we'll add zero and when using reduce you have the option to pass the second argument which is the starting value to accumulate from which in our case would just be zero so now we know that we have three 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 a another array method just for that called a race sort it allows you to pass in a compare function to sort the array based on whatever logic you want once we have that sort of 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 going to 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 fire ship IO thanks for watching and I will talk to you soon [Music]
Info
Channel: Fireship
Views: 258,732
Rating: 4.9462023 out of 5
Keywords: webdev, app development, javascript, lesson, tutorial, js, ts, javascript loops, js loop, js tutorial, for loop, foreach loop, for-of loop, iteration, symbol iterator
Id: x7Xzvm0iLCI
Channel Id: undefined
Length: 8min 35sec (515 seconds)
Published: Wed Jan 16 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.