JavaScript Loops

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up guys hope you're doing well today we'll go through the various ways javascript provides to iterate through loops let's go okay let's loop through their loops and by the way I'm using the visual studio code editor I've created a JavaScript file which I named loop dot J's in order to run the code for this file and display the results here in the output I'm using the code runner visual studio code extension and now let's start with the classics and more specifically their for-loop so let's create a basic for loop for let I equals 0 I less than let's say 5 I plus plus and let's just look I console dot look I this is the starting point or initialization statement in our case we initialize the counter or loop variable to zero of course variable could have any name but it's like a convention to use I which stands for index as the loop variable and we use the semicolon to end the statement next comes the continuation condition which will be evaluated before each loop iteration and if it relates to true then the loop code block will be executed otherwise loop execution will stop and program will proceed to executing the expressions following the loop and finally at the end of each loop iteration we use this final expression to update the value of the loop variable before we evaluating the continuation condition in our case we just increase its value by 1 by using the plus plus operator we could of course alternatively use plus equals 1 or I equals I plus 1 all these produce the same result they increase the value of the counter by 1 so let's save and test in order to run the code we right-click and hit run code or use this shortcut ctrl + Alt + n and as expected we get 0 up until 4 locked in the console why don't we also get 5 well because when I becomes 5 then the continuation condition is not met any more it becomes false and the loop execution stops if we also wanted to print 5 we could use less than or equal to 5 here and let's run so this time we also get five locked in the console instead of going forward we could of course go backwards starting from five continue while I is greater than or equal to zero and decrease I by one after each iteration let's save and see the result indeed this time we get five to zero instead of zero to five nice however in this tutorial we'll mainly concentrate in looping through arrays so let's define an array here Const my array equals and an array is basically just a list of items let's say a B and C and in order to look through the entire array using a for loop we have four let I equals zero since arrays are zero based meaning that index for first item is zero for second is one for third is two etc so for an array with three items maximum index is 2 and in general for an array with n items maximum index is n minus 1 so continuation condition should be while I is less than the length of the array which is 3 however for arrays and array like objects in general we have the length property which returns the length of the array so let's use this my array dot length I lost plus we are now ready to use indexes to iterate through my array items and instead of just logging the index here let's use template literals index I and let's also display the value for the if' item and how can we get the value for item with index I in my array well that's simple my array I nice let's save and run the code indeed for each array item we get the index and the value we can also interrupt or break out of a for loop using the break statement so for example if I equals to 1 let's exit the loop using the break statement let's save and see the result indeed we only get the zero indexed element since then I becomes one and loop is interrupted and we can also use the continue statement to fast forward to the next iteration of a for loop so for example if I equals to one we can use the continue statement to skip the execution of following expressions and move on to the next iteration so let's save and see the result indeed we get all items except for the item with index 1 okay let's proceed to the wild loop the while loop looks through a code block as long as a specified condition is true the syntax for a while loop is the wild keyword in here goes the condition and here the code block to be executed so while this condition evaluates to true this code block will be executed until condition evaluates to false in this case the loop will end and the expressions following the while loop will be executed so if for example we used this condition then this code block would never be executed and on the other hand if we used this condition which obviously always evaluates to true then this loop would never end we would have an infinite loop since this code block would be executed code and code forever which would cause our browser to crash now we usually use a variable with the condition for example while I is less than five and in this case we should first initialize the variable before the loop so let I be equal to zero okay so we initialize the variable we have the continuation condition here and let's look hi but before running the code we should do one more thing and that is increasing the variable value because guys if we didn't do this then let's see what would happen is said to be equal to zero here while I is less than five is a continuation condition zero is indeed less than five so this code block would be executed and I which is zero would be locked in the console then this expression would be reevaluated and zero is still less than five so this would be executed again then it would be reevaluated zero would still be less than five and this would be executed and you get that the point is good always be evaluated to true and therefore we would get into an infinite loop so in order to ensure that we would exit the loop at some point we should increase I okay let's save and around the code indeed we get zero AB until four o'clock in the console if we also wanted number five locked in the console then we should rather use in the continuation condition why I is less than or equal to five so let's rerun the code indeed this time we get 0 up until 5 and in order to loop through my array and lock the index and value for each element in the array let's see what changes we have to do so let i equals zero yeah we want to start from zero index while I is less than my RA dot length and we want to lock the index and value for each element in the array I plus plus this remains the same so let's save and run the code indeed we get the index and value for each element now comparing the two loops we can see that in both cases we have the initialization statement the continuation condition and the increment expression so now you might be wondering when and why use one loop over the other well we usually use a for loop when the number of iterations is known in advance and therefore in our example it would make more sense to use a for loop since we know beforehand the number of iterations while loop should be used when number of iterations is not known in advance and we only know the ending condition for example suppose we request the user to enter a number between 1 and 10 and while the user enters numbers beyond this range we want to keep asking the user to enter a correct number in this case we don't know beforehand how many times this procedure will be repeated and therefore a while loop would be the appropriate loop similarly to the for loop we can use the break keyword to break out of the loop for example let's interrupt the loop if I equals to 1 so we expect only the first element to be locked in the console let's save and run the code very nice and we can also use the continue keyword in order to fast forward to the next iteration of the loop so if I equals to 1 by using the continue keyword we skip execution of the following expressions and move on to the next iteration however can you spot the problem here by skipping execution of this line of code I will not increase and will still be equal to 1 and we will fall into an infinite loop in order to avoid this trap we should make sure to increase the value of I before continuing so let's save and see the result indeed we get all elements except for the element with index 1 okay let's move on to the do-while loop the do-while loop is just a variant of the while loop the only difference is that the loop we execute the code block at least once before checking if the condition is true then it will repeat the loop as long as the condition is true in a similar manner as the white loop the syntax for do-while loop is do yeah goes the code block the executed and here while and their condition okay and let's see how we can loop through my array using a do-while loop it's very similar to while loop so I will just copy/paste links this is the initialization statement this will be the code block and the wild condition so initially I will be set to be equal to zero then this code block will be executed no matter what the evaluation of this condition is then if this condition evaluates to true this code block will be executed again if these are evaluates to true these will be executed again etc etc until this becomes false and in this case the loop will come to an end and the program will continue executing expressions following the do-while loop okay let's save and run the code in this case we expect all elements to be logged in the console all right here we are now just in order to show that this code block will be executed at least once no matter what the valuation of this condition is let's make sure that this condition will evaluate to false so is a 2 B equal to 0 here and increased here so there is no way I will be less than 0 so this will evaluate to false let's save and see the result as expected this code block is executed once then this evaluates to false and the do-while loop stops okay and that's all with the do-while loop and of course similarly to the while loop we can use the break and continue keywords now if you don't like the do-while loop you can just use the while loop and easily get around this case if necessary excellent and now that we are done with the classics let's move on to there for each method for each method was introduced in es5 Eggman script 5 and it executes a provided function once for each array element in ascending order so first the callback function is executed for the first element in the array then the second etc okay let's look through my array using the for each method in order to lock the index and value for each element in the array so for each element in the array this function will be called the function takes up to three arguments the first argument is required and corresponds to the value of the current element so another net good name would be item or value but let's use LM which stands for element the second argument is optional and corresponds to the array index of the current element and the third one is also optional and corresponds to the array therefore each method was called upon in our case it corresponds to my array however in our example we want to make use of this so let's remove it and now let's lock the index and value for each element in the array so index is index and value is LM let's save and run the code indeed we get the index and value for each element and we could rewrite the callback function using arrow functions syntax which was introduced in es6 so we don't need the function keyword is are the parameters the fat arrow and since we only have one statement we don't need the curly brackets let's save and run the code okay works as intended and if for example we were only interested in the array element value then in this case we would only have one parameter and therefore parentheses would be optional so let's remove them if we run the code now then we expect to get an error since index is not defined let's do it indeed we get an error index is not defined so let's remove it and rerun the code very nice now why use the forage method over the for-loop well the main argument in favor of forage method is readability and that mainly because with the for each method we don't have to define and use a temporary variable as index in order to loop through the array moreover with a forage method we don't have to think about the condition statement avoiding the what we call off by one error which is iterating one time too many or one time to view on the other hand a for-loop which does not necessarily involve an RA is more flexible since it allows to choose the iteration algorithm we want for example if we only wanted to loop through every second element in the array all we have to do is increase I by 2 instead of 1 at the end of each iteration which we can't do with a for each method moreover for loop is generally faster than for each however for each is still fast enough at least in most cases browser support wouldn't be an issue since by now the for each method is supported by all browsers needless to say that for while and do-while loops a universal supported just keep in mind that arrow functions are not yet supported by all browsers and therefore you might want to use this way to achieve cross browser compatibility and finally contrary to a for-loop we can't break out of a for each loop or continue to next iteration using the break or continue keywords so if for example we tried to break out of the for each loop if index is equal to one then we would get an error let's save and run the code you indeed we get an error in legal break statement now in year six the four of loop was introduced which combines the conciseness of forage loop with ability to break and continue so the four of loop iterates over iterable objects such as strings arrays and array like object and let's use the for of loop to iterate through the elements of my array so for let L M of my array and again all we want to do here is lock the value for each element so let's save and around the code indeed for each element in the array we get the corresponding value locked in a console now note that this loop creates a new scope in every iteration and therefore we can safely use the Const constant instead of lead given of course that we will not reassign the variable inside the code block so let's save and run the code you works fine now the four of loop doesn't give access to the index of the current element and in most cases that's enough and it's also shorter however we can also get the index using the entries method over the original array which returns an array of index and value for each element of the original array so let's do this or Const index and LM of my RA dot and T's and this time we want to look both index and value so let's save and run the code indeed we get the index and value for each element nice and as already mentioned with the four of loop we can use the break or continue keyword to break out of the loop or continue the next iteration so for example if index equals to one let's break out of the loop save and around the coat indeed we only get the first element and let's also test the continue statement so if I equals to one let's continue to next iteration save and run the code indeed we get all elements except for the element with index 1 and before proceeding let's check browser support for the four of loop which is quite good however the four of loop is not supported by Internet Explorer also the four of loop is slower than the for each method however in most cases it is still sufficiently fast okay let's proceed to the for in loop the for in loop iterates over all enumerable properties of an object giving the property names note that it should not be used to iterate over an array where the index order is important since it does not guarantee that it will return the indexes in any particular order and although the for in loop shouldn't be used to iterate over the elements of an array just out of curiosity let's use it to loop through my array so for let and instead of LM let's use property since the for in loop loops through the property names of the object in the case of an array property name is the actual index so for led property in my array again let's look the index and value of each element so index in this case is property and value is my RA property so let's save and run the code in this case the for in loop loops through my array keeping the correct order however as already mentioned this is not the correct usage of the for in loop which should rather be used to iterate over object property names so for testing purposes let's create an object and loop through it using the for in loop Const my object equals and let's name the first property a and give it the value one second property B with value too third property see with value three and now let's use the for in loop to loop through my object via property names and let's look the property names and the corresponding values we get the values using the property names as keys so let's save and run the code we get the property names however we don't get the value because I forgot to change my array to my object so let's save and run again nice now we get the property names and the corresponding values and similarly to the four of loop we can use Const here instead of lead let's save and run the code excellent and regarding the browser support for the for in loop we can see that it does quite well and that's all basically we won't expand any further however before wrapping up let's try to test the difference in speed between different loops or starters let's define the number of iterations let's say 1 million 1 2 3 4 5 6 and let's also define an array with the same length this creates an array without items all its elements are undefined but with a given length in order to capture the elapsed time we'll use the console dot time method with some labor combined with the console dot time and method with the same labor so for example in order to time 1 million iterations using the for loop let's name the label or and let's create the loop here for let I equals 0 I less than Nam I plus plus and I'll keep the loops as plain as possible so that time won't be affected by other factors so I will leave this empty let's save and run the code so it takes about 7 min seconds for 1 million iterations using the for loop this is too fast I don't know how reliable results will be maybe we should increase number of iterations and by the way I'm just using an average laptop but anyways let's also add there other loops and see what happens working in a similar manner and doing the bare minimum let me speed code this part in order to spare you some time and I'll be right back you all right so we have the for a while the forage and the four of Luke's notice that I didn't include the for in loop since it has a different use all four loops here can be used to iterate through arrays so let's save and run the code okay first observation here is that all loops seem to be quite fast therefore of loop which seems to be the slowest performs 1 million iterations in about 34 milliseconds so if you don't expect to have more than a million iterations then maybe speed shouldn't be a determining factor on which loop to use unless of course speed is very important for your program and every millisecond counts now since loops are completed very fast especially the first three I would suggest to increase number of iterations in order to be able to maybe jump to safer conclusions so let's make it 10 million iterations save and let's run okay now we are talking the while loop is the fastest with approximately seven milliseconds for ten million iterations next comes the for loop which is again very fast with approximately 15 milliseconds for ten million iterations the for loop is about two times slower than the while loop next comes the for each loop with about 55 milliseconds for ten million iterations right tolerable I think the for each loop is about three to four times slower than the for loop and finally the for of loop which is the slowest takes about two hundred and two hundred and seventy four milliseconds or ten million iterations which is about five times slower than the for each loop and I think that at this point speed starts becoming an issue for the especially for therefore of loop nice however just to be more confident about the results let's increase number of iterations to 100 millions let's save and run the code you that took a while okay what I mainly was interest about what was the order so these two are together this time why is a bit faster than four but not twice as fast doesn't matter because they are both very fast and difference is insignificant then comes therefore each and then therefore off nice let's end our little experiment here so in this video we've discussed the various ways Java Script provides to iterate through loops we've been through the for the while that too wild the forage the for off as well as the for in looks we mainly concentrated in looping through arrays and at this point we should mention that besides these loops modern JavaScript also provides many methods for working with arrays such as map if they're reduce sort some every etc that's all for now guys hope you got some value out of this video for any questions suggestions or just to say hi please use the comment section below hit the like button if you like this video subscribe if you want more till next time keep coding keep improving and enjoy the journey take care bye
Info
Channel: Coding Journey
Views: 12,186
Rating: undefined out of 5
Keywords: javascript loops, js loops, loops, for loop, while loop, do while loop, forEach, forEach js, forEach javascript, for of loop, for of javascript, for in loop, for in javascript, javascript iterations, javascript, loop, for loops, while loops, iteration, javascript loops tutorial, loops programming, programming, coding, web development, front end, front-end, back end, back-end, es5, es6, learn javascript, web tutorials, ui, ux, coding journey, how-to, javascript loops explained
Id: rTDAAhUgJZM
Channel Id: undefined
Length: 39min 53sec (2393 seconds)
Published: Tue Mar 26 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.