TeachingBee

JavaScript Looping : 5 Awesome Ways to Use Them

javascript looping

Introduction

The term javascript looping refers to a piece of code that permits you to run a piece of code for a specified number of times, possibly changing the values of variables every when the program is run. This way it’s possible to compress certain tasks into only a few lines instead of writing the same code repeatedly in the script, and fatigue your fingers.

Loops are beneficial as they let you duplicate the same lines without having to type them, or by using cut and paste within the text editor. This will not only save you the effort and time of typing the same codes, but it also prevents mistakes in typing on the repeated lines. It also allows you to alter the value of one or more variables every time you go through the loop. This helps you avoid the effort and time of typing lines that are just a little different from the line before.

In a simpler example, imagine you want to type a sentence 15 times by using JavaScript.In order to do this you may need write the following statements 15 times:

document.write("Let’s Understand javascript looping !");

Cut/Paste can make the task easier, but it would still be a bit tedious, especially if you decide to write the sentence 100-200 times instead. With a loop, you could write that document.write() statement just one time and then adjust the number of times you want it to written.

Repeat this block 100 times 
{ 
document.write("I only had to type this once!");
 }

In order to see how loops can really be helpful to you, you need to take a look at the different loop structures that you can use in JavaScript. The loop structures covered in this section are the for, while, and do while loops in javascript.

For loops in Javascript

The structure of a for loops in javascript is very similar to that of the conditional blocks. The only major differences are that a loop serves a different purpose and, as a result, the first line is different.

The first line of a for loop is :

for (var count=1; count<20; count++)

The first thing you see is the for keyword. This is followed by a set of parentheses with three statements inside. These three statements tell the loop how many times it should repeat.

  1. The first statement (var count=1) creates a variable named count and assigns it an initial value of 1. This initial value can be any number. This number is used as a starting point for the number of times the loop will repeat.
  2. The next statement (count<20) tells the loop when to stop running. The loop will stop running based on this conditional statement. The condition here is to stop only when the variable count is no longer less than 20.
  3. The last statement in the set (count ++) determines the rate at which the variable is changed and whether it gets larger or smaller each time.

To finish the structure, you insert the curly brackets to enclose the code that you wish to use within the loop. The full structure of for loops in javascript is:

for (count=1; count<20; count++) { 
JavaScript Code Here 
}

Nested for loops in javascript

You can nest as many levels deep as you can handle. For now, you will just nest one loop within another. The following example shows a for loop within a for loop:

for (var count=1; count<20; count++) {
document.write("Inside outer loop!"); 
for (var nestcount=1; nestcount< 7; nestcount++) {
document.write("Inside nested loop!");
}
}

While loop in Javascript

A while loop simply examines a brief comparison and continues until the comparison ceases to be accurate. For a start review the basic syntax of the initial line in a loop which is (count<20).

While doesn’t create a variable as a for statement could. When you use the while loop be sure to declare the variable you want to utilise and assign it a value prior to you put it in the. 

The following code demonstrates the basic outline of a fully while loop, so you can observe the way it appears:

var count=1; 
while (count < 20) {
JavaScript Code Here 
count++;
}

First, notice that the value of 1 is assigned to the variable count before the loop begins. This is important to do so that the loop will run the way you expect it to run.

This loop is set up to repeat twenty times, given the initial value of the variable and the increase in the value ofthe variable by 1 each time through (count++).

In a while loop, you must also remember to change the value of the variable you use so that you do not get stuck in a permanent loop.

Do While loop in Javascript

The do while loop in javascript is special because the code within the loop is executed at least once, even if the comparison used would return false the first time.

A comparison that returns false in other loops on the first attempt would cause them never to be executed. In the case of a do while loop, the loop is executed once, and then the comparison is used each time afterward to determine whether or not it should repeat.

The following is an example of a do while loop that will run nine times:

var count=1; 
do { 
document.write("Do while javascript looping !!");  
count++; 
} while (count < 10);

Notice the keyword do and the opening curly bracket are the only things on the first line of the block in the preceding code. Then, when the block is complete, you see the while statement and comparison.

The do keyword is how you ensure the code block is executed at least once. After that, the browser checks to see that the comparison returns true before repeating.

In this case, the loop repeats nine times since the variable count starts at 1 and is increased by 1 each time through. When the value of count reaches 10, the loop is skipped and no longer executed.

JavaScript For In Loop

JavaScript allows you to utilize the for-in loop to assist you manipulate objects , as well as using the statement with to gain access certain objects more quickly. The for-in loop lets users to move over the attributes of objects to display them , or modify the values of objects.

 The following code illustrates the basic structure that a for-in loop follows

for (var variable_name in object_name) {
 JavaScript Code Here
}

Imagine you want to go over the various properties in a Car instance to display the value of every item on the web page. The for-in loop lets you to accomplish this without having to input each property’s name, such as in the following code:

function car(seats, engine, radio) { 
this.seats=seats; 
this.engine=engine; 
this.radio=radio;
}
var car_instance= new car("leather","V-8","Stereo"); 

for (var prop_name in car_instance){
document.write(work_car[prop_name]);
}

For Each Loop in Javascript

ForEach is an JavaScript array method. It’s used to execute an operation on every element within an array. Sets, lists and other similar to list objects are compatible with the forEach method.

We’ll create an expression loop that shows an array of fruits in the console. In lieu of using the for loop we’ll use the forEach loop. This is because we’re working with a list.

The code below prints each value from a company’s list in the console

The following code prints each value from a list of companies to the console:

const fruits = ["Apple", "Banana", "Cherry"]; 

fruits.forEach(f => {
console.log(f);
});

For loop vs For Each loop in javascript

With a forEach loop, we can access each item in our list individually. In our last example, we created the variable “fruits”. This variable represented an individual fruit over which our forEach loop was iterating.

ForEach loops accept a callback function whereas for loops do not. In a for loop, all of your code is enclosed in the main body of the loop. In a forEach loop, you must write a function which will be executed for each item in the list over which you are iterating.

const fruits = ["Apple", "Banana", "Cherry"]; 

function printValue(fruit) { 
console.log(fruit);
}

companies.forEach(printValue);

Conclusion

That’s it an introduction to loops and ways to make use of them, along with a basic explanations of for and do…while loop in javascript. In the moment, we might not use loops as often. When we get into more complex situations that involve the collection of data, elements within the DOM of your computer, manipulations in text and more that require loops, we’ll likely use them quite a bit more. Basically…keep all the data that we’ve learned here in near and happy javascript looping.

Got a question or just want to chat? Comment below or drop by our forums, where a bunch of the friendliest people you’ll ever run into will be happy to help you out!

90% of Tech Recruiters Judge This In Seconds! 👩‍💻🔍

Don’t let your resume be the weak link. Discover how to make a strong first impression with our free technical resume review!

Related Articles

angular js vs React

Angular JS vs React: Which is Better?

Introduction JavaScript is a client-side scripting language used to provide dynamic attributes as well as features to HTML web pages . JavaScript was created to assist the browser by enabling

Why Aren’t You Getting Interview Calls? 📞❌

It might just be your resume. Let us pinpoint the problem for free and supercharge your job search. 

Newsletter

Don’t miss out! Subscribe now

Log In