Master JavaScript Loops
Master JavaScript Loops JavaScript is becoming increasingly clear to us as we gain a better understanding of it. A very important control flow concept will be discussed in this article: loops.
In a loop, a code block is executed a certain number of times. Many things can be done with loops, including repeating operations over and over again and iterating over data sets, arrays, and objects. Instead of copying and pasting code just underneath the original, you should probably use a loop.
The basic concept of loops will be discussed first, and then nesting loops, which is basically loops within loops, will be discussed next. In addition, we will discuss how to loop over two complex constructs we have already encountered, arrays and objects. The last thing we’ll do is introduce two keywords related to loops, break and continue, that will allow us to control the loop’s flow even more.
The article does not cover one topic related to loops. This is the built-in method foreach. Arrays can be looped over with this method, using the arrow function. Foreach is not included here, since we will discuss them in the next article.
This articlewill cover the following loops:
while loop
do while loop
for loop
for in
for of loop
while loops
The while loop is the first loop we will discuss. While loops execute a set of instructions until an expression is evaluated as true. Below is a snippet demonstrating the while loop syntax:
In a while loop, only if the condition is true will the code inside run, so if it is false to begin with, the code will not run.
Using a while loop, we can print the numbers 0 to 10 to the console:
As a result, we will have the following output:
The following steps are taking place:
Set the value of i to zero and create a variable called i
If i is smaller than 10, start the while loop and check the condition
When the condition is true, the code increases i by one and logs i
There is still a difference between 1 and 10 when the condition is reevaluated
When the condition is true, the code increases i by one and logs i
Until I reach 10, I will keep logging and increasing
The loop ends because 10 cannot be smaller than 10
An array of values can be searched for by a while loop, as follows:
The shift method is used to delete the first value from the array when the first value doesn’t match a certain value. Are you familiar with this method? The array’s first element is removed. As a result, the first value is checked again on the next iteration. It will log the value to the console if it stumbles across the value, and it will change notFound to false if it finds it. The loop has been completed after that last iteration. The following will be output:
Can you explain why the while condition includes the && someArray.length > 0? Without it, we would get stuck in an infinite loop if the value we were seeking wasn’t in the array. In order to continue our code, we also end things if our value is not present.
It is also possible to do more sophisticated things with loops very easily. A loop makes it easy to fill an array with Fibonacci sequences:
Beginning with 0 and 1, each Fibonacci value is the sum of the two previous ones. The while loop can be used to accomplish this. Each time we iterate, we create two numbers that change. Due to the fibonacciArray’s length, we have limited the number of iterations to the number of iterations. Whenever the array is longer than 25 in this case, the loop will end.
There is a need to create a temporary variable to store values for what is to come next for nr2. The first number is pushed into the array every time we iterate. Logging the array shows that the numbers quickly rise to quite high levels. How would you feel if you had to generate these values one by one in your code?
do while loops
There are times when the code block needs to be executed at least once. It is necessary to ask the user at least once if you need valid input. The same is true for connecting to a database or another external source: you need to do it at least once to be successful. So long as you didn’t get the result you wanted, you will probably have to do so. Do while loops can be used in these situations.
The syntax is as follows:
The do block is executed, and then the while block is evaluated. When the condition is true, the do block will be executed again. As long as the condition in the while remains true, this will continue to happen.
It is possible to get user input by using the prompt() method. The user will be asked for a number between 0 and 100 using a do while loop.
Here is the output; to get the number, you’ll have to enter it yourself in the console.
This is all user input behind the >. It is part of the code; the console adds it to make it clear between console output (Enter a number between 0 and 100) and console input (-50, 150, and 34).
Because the condition in the while block was true the first two times, it asks three times. In the while block, the condition became false at 34, and the loop ended.
for loops
There are special loops called for loops. At first, the syntax might seem confusing, but once you get used to it, you will find it extremely useful.
This is how the syntax looks:
Three parts are separated by semicolons between parentheses following the for statement. In the first one, variables are initialized for use within the for loop. Second, there is a condition: the loop will iterate as long as the condition is true. It is only checked when the condition evaluates to true that the variable is initialized before the first iteration. Lastly, we have a statement. Every iteration of this statement executes this statement. A for loop looks like this:
Variables need to be initialized.
Make sure everything is in order.
The code block should be executed if the condition is true. This is where the loop ends if the condition is false.
The third part of the statement should be executed (for example, i++).
Revert to step 2 if necessary.
In this example, we log the numbers from 0 to 10 (except 10) to the console:
The program begins by creating a variable, i, and setting it to zero. This is followed by a check to see if i is smaller than 10. The log statement will be executed if it is. Afterward, i++ will be executed and i will be increased by one.
The value of i would not change if we don’t increase it, which would result in an infinite loop. Every loop should be aware of this!
A second check is performed on the condition. This process continues until a value of 10 is reached. Since 10 cannot be smaller than 10, the loop has been completed, and the numbers 0 to 9 have been logged.
In addition to creating a sequence and adding values to an array, we can also use a for loop to do so.
As a result of this loop, here is what the array looks like:
The block of code will increment the array starting with an initial value of 0 for i, since the loop runs 100 times with the block of code. As a result, the array consists of 100 items and has a count of 0–99. Array values match the index values of their corresponding items because arrays start with a value of zero.
It is also possible to create a set of only even values in an array:
As a result, we have the following array:
A for loop usually has i++ as the third part, but there are other statements you can use in there. As a result, we create an array with only even numbers by using i = i + 2 every time.
Nested loops
In some cases, a loop inside a loop may be necessary. Nesting a loop inside another loop is referred to as nested looping. Often, it does not solve the problem effectively. Sometimes it’s a perfectly acceptable solution to a problem, but it can also be a sign of poorly written code.
As an example of a while loop, here’s how it would look:
It is also possible to nest loops with for loops or with a combination of for and while loops. It is possible to nest loops at different levels.
Nesting loops can be used to create arrays of arrays, for example. A top-level array is created with the outer loop, and values are added with the inner loop.
The following is what happens when we log this array:
It appears that the output is a collection of arrays with values ranging from 0 to 6.
Using nested loops, we created an array within an array, so we can manipulate rows and columns after constructing this loop. Thus, tabular data can be created using nested loops. The console.table() method can be used to display this output instead, as follows:
The following will be output:
┌─────────┬───┬───┬───┬───┬───┬───┬───┐│ (index) │ 0 │ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │├─────────┼───┼───┼───┼───┼───┼───┼───┤│ 0 │ 0 │ 1 │ 2 │ 3 │ 4 │ 5 │ 6 ││ 1 │ 0 │ 1 │ 2 │ 3 │ 4 │ 5 │ 6 ││ 2 │ 0 │ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │└─────────┴───┴───┴───┴───┴───┴───┴───┘
Loops and arrays
Consider loops and arrays if you’re still not convinced that loops are extremely useful. Arrays are much easier to work with when you use loops.
For loops or while loops, we can combine the length property with the condition part to loop over arrays. In the case of a for loop, it would look like this:
Here’s a simple example of logging every array value:
The output will be as follows:
Our index’s maximum value is determined by its length property. There is no starting point for the index, but there is for the length. Indexes are always one smaller than lengths. Thus, we increase the length of the array to loop over its values.
At the moment, we are simply printing the values; we aren’t doing anything very interesting. Alternatively, we could loop through the array changing its values, like this:
Our names have been concatenated with hello. In the loop, the array is changed, and after the loop has run, the array will contain this information:
There are endless possibilities here. It is possible to send data to the database per value when an array appears somewhere in the application. It is possible to modify data by values, or even filter it, as follows:
A string start with a certain character can be checked using the startsWith() method. It checks if the name begins with the letter M in this case.
As a result, we get:
It’s important to be careful here, however. Since the next value gets the index of the recently deleted one, and i is incremented and moves on to the next value, removing the item instead of deleting it would result in the next value being skipped.
In your opinion, what does this one do:
An infinite loop occurs here in your program. Since the loop length grows with each iteration, i will never exceed or equal length since a value is added every time.
for of loop
The for of loop is another way to iterate over an array’s elements. In contrast to the regular loop, this loop cannot change the index value, but it is very useful for processing values.
The syntax is as follows:
Using this loop, we can log the names array using the following: “For every value of the array, call it variableName and do the following.”
A temporary variable is required; in this case, it is called name. The current iteration’s value is put into this, and after iteration, it is replaced with the next iteration’s value. The following output is generated by this code:
This array cannot be modified, but it can be stored in a database or a file, or sent elsewhere. This prevents us from getting stuck in an infinite loop or skipping values accidentally.