×

Javascript loops

Loops in JavaScript: Loops are used to execute a specific piece or block of code repeatedly until the given condition is satisfied.

What is a Loop?

Almost all loops contain a certain process and this process is defined by the users according to their requirements. For example, the following processes can be defined by the users in a loop:

  • Fetching values from an array
  • Performing some operations on the values of an array
  • Checking a given condition such as the given maximum counter/number is reached or not.

The basic idea behind the creation of a loop is to automate the repetitive operations inside the program to reduce the size of code as well as to save time.

Types of Loops in JavaScript

There are basically five types of loops in the JavaScript that are as follows:

  1. While
  2. Do.. While
  3. For
  4. For…in
  5. For…of

Let’s understand each type of the loop with help of an example.

  1. While Loop:-

It is one of the easiest looping statements in the JavaScript language.

A block of code in the "while" looping statement is executed continuously until the given condition becomes false. We can also say that as long as the given condition evaluates to true, the block of code keeps executing.

Let’s see, how the “while loop” works with help of a diagram:

Javascript loop

Syntax of While Loop statement

while(condition to be checked) {
    // Code to be executed
}

Note: Remember one thing that you must use conditions that must be false on a certain point, Otherwise your looping statement will keep executing for the infinite number of times.

Example

Program

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>While Loop statement</title>
</head>
<body>
<script>
vari = 0;
while(i<= 9) {   
document.write("<p>The number is " + i + "</p>");
i++;
    }
</script>
</body>
</html>

In the above program, we have used a “while” loop statement to print the integers from 0 to 9. In the place of condition, we have used an expression (i<=9);

Do..while Loop statement

The "do-while" loop statement is an extended version of the "while" loop statement in which the condition checking process is placed at the end of the loop statement.

Another thing that separates the "while" loop from the "do ... while" loop is that a block of "do..while" loop code runs for at least one time, even if the given condition gets false in the first attempt.

Let’s see, how the “Do…while loop” works with help of a diagram:

Javascript loop

Syntax of “Do..While” loop statement

do {
    // Code/instructions to be executed
}
while(condition);

Let's understand this in more detail with the help of an example:

Program

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Do-While Loop</title>
</head>
<body>
<script>
vari = 0;
do {
document.write("<p>The number is " + i + "</p>");
i++;
    }
while(i<= 4);//this is the condition checking statement
</script>
</body>
</html>

In the given program, we have defined a "do..while" loop for printing integers 0 to 4. When the counter of the "do..while" loop exceeds the specified value (4), the condition becomes false, and the execution of the loop statement gets terminated.

Output

Let’s see another example in which condition is false in first attempt.

Javascript loop

Program

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Do-While Loop</title>
</head>
<body>
<script>
var i = 0;
do {
document.write("<p>The number is " + i + "</p>");
i++;
    }
while(i< 0); // this is the condition checking statement
</script>
</body>
</html>

In the above program, we have defined a “do…while” loop to print integers but in the condition checking part, we have mentioned the value (i<0), which is already false. Let’s see what happens when the condition gets false in the first try.

Output

Javascript loop

We get (0) output in the above program, because as we have already discussed that the code block given in the "Do...While" loop is executed at least for once. It does not matter whether the condition is getting right or wrong at first.

For Loop Statement

In the "for" loop statement, a block of code keeps executing until the given specific condition becomes false. It is typically used to run a set of instructions for a particular number of times.

Let’s see, how the “For loop” works with help of a diagram:

Javascript loop

You can understand the "For" loop statement more easily by seeing the syntax given below:

for (statement A; statement B; statement C)
{
 // code block to be executed or A set of instructions
}
  1. Statement A:- In this statement, the initial condition is defined that is executed only once before the execution of the block of code given in the curly braces.
  • Statement B:-In this statement, the final condition(like "a<4") has been  defined, and the code block given in the curly brace is executed repeatedly until this condition becomes false.
  • Statement c:-The condition/expression given in it (egi ++, i--) is executed on every iteration.

For Example

for (a = 0; a< 5; a++)
{
  text += "The number is " + i + "<br>";
}

As we can see, the statement A defines a variable "a = 0" before starting the loop. Statement B defines the specific condition and the given code block gets executed until this condition become false.

Statement C makes increment (of +1) in the value on every iteration.

Let’s understand “for” loop statement with the help of a program:

Program

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>For Loop Statement</title>
</head>
<body>
<script>
    // Creating arrays
var colors = ["Red", "Yellow", "Green", "Orange"];
var cities = ["London", "Paris", "New York"];
    // Printing array values
for(i=0;i<colors.length;i++)
{
document.write(colors[i] + "<br>");
}  </script>
</body>
</html>

In the above-given program, we have defined a “for” loop statement to print the values of the array “colors”.

Output

Javascript loop

For…In Loop Statement

In JavaScript, the "For...In" loop is a different kind of Looping statement. It loops through the elements of the arrays, or properties of the object. We can also say that it iterates on the elements of the arrays or properties of the object.

Syntax of For…In Loop Statement

for(variable in the  object)
{
    // Code to be executed
}

Note: One important thing in “for...in “ loop statement is that the value of the counter is not in the form of integers but it is given in the form of string.

Example

Program

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>For...In Loop</title>
</head>
<body>
<script>
    // An object with some properties
var person = {"name": "Jame", "surname": "Doe", "age": "36"};
    // Loop through all the properties in the object 
for(var prop in person) { 
document.write("<p>" + prop + " = " + person[prop] + "</p>");
    }
</script>
</body>
</html>

In above program, we have defined the “for..in” statement to print the properties of object and element of the object.

Output

Javascript loop

It is also possible to loop through the elements of the array using “for…in” loop as shown in the given program

Example

Porgram

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>For-In Loop</title>
</head>
<body>
<script>
    // An array with some elements
var colors = ["Red", "Yellow", "Green", "Orange"];    
    // Loop through all the elements in the array
for(vari in colors) { 
document.write("<p>" + colors[i] + "</p>");
    }
</script>
</body>
</html>

In the above program, we have defined the for…in loop to print the values of the given array.

Output

Javascript loop

For…of Loop statement

You can use the “for…of” loops over all iterable objects such as strings or arrays. This “for…of “ loop statement was introduced in the javascriptES6.

The generic syntax of “for…of” loop statement

for (variable of iterable)
{
  // code block to be executed
}

In the variable, the value of the next property is assigned to the variable for each iteration.

Iterable- These are objects that have iterable properties.

Let’s understand for…of looping statement with help of an example:

Program

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>for...of Looping statement of JavaScript ES6</title>
</head>
<body>
<script>
    // Iterating over array
var characters = ["o", "r", "a", "n", "g", "e"];
for(var char of characters) {
document.write(char + ","); // orange
    }
document.write("<hr>");
    // Iterating over string
var msg = "Hello World!";
for(var character of msg) {
document.write(character + "<br>"); // H,e,l,l,o, ,W,o,r,l,d,!
    }
</script>
</body>
</html>

In the above program, we have used the for…of looping statement of the JavaScript ES6.

First, we have created a string (e.g., var/let msg=”Hello World!”), to print this, we defined for..of loop (e.g., “for(var character of msg)”, in which we created another variable (e.g., var/let character) to print the characters of the string.

Output

Javascript loop

Note: We cannot use the for…of looping statement for the non-iterable objects, but if we want to iterate the properties of a non-iterable object, we can use the for…in looping statement.


Related Topics

Javascript input maxlength

Various attributes often accompany the input tag in HTML to change the properties of the input field. Maxlength() is one such attribute. The maxLength attribute defines the maximum number of characters...

2 minutes read.

Javascript Page Redirect

The window.location object can be used to get the current page address (URL) and to redirect browser to new page. In some websites when we visit, we face a situation where we...

3 minutes read.

Functional Programming in JavaScript

Most developers work with object-oriented programming while developing their applications, but sometimes they need to change their approach to solve some specific tasks. Although mostly we tend to go for...

6 minutes read.

D3.js Tutorial

Introduction of D3.js D3.js is referred to as a JavaScript library that is used to manipulate the documents according to the data. The intensity of D3 is based on web standards...

5 minutes read.

Synchronous and Asynchronous in JavaScript

JavaScript is a powerful and versatile language that is used all over the web, from small websites to large applications. It is essential for developers to understand the differences between...

9 minutes read.

Javascript Dialog Box

A JavaScript dialog box is predefined function which is used to perform different task. Some functions are used in JavaScript Dialog box. FunctionDescriptionalert()To give alert message to userprompt()To input value from...

2 minutes read.

Javascript Example

What is JavaScript? JavaScript is a highly versatile programming language. It provides the capability to add interactivity to static web pages, which are designed with HTML and CSS. It also provides...

5 minutes read.

JavaScript p5.js

Introduction to p5.js P5.js is a JavaScript library for creative programming. It is built on Processing, a coding environment for creativity. Processing's major goal is to make it as simple as...

4 minutes read.

Javascript Find Object In Array

What is find() method? It returns the value of the first element in the given array that fulfils the given testing function. However, if no values from the array are able...

3 minutes read.

What is Ternary Operator in JavaScript?

In some cases, a ternary operator can be used instead of an if-else expression. A ternary operator examines a condition and then runs a block of code in response to...

4 minutes read.

Javascript Number

The Number object is a wrapper object which allows you to work with numerical values. The number object is created using the Number() constructor.It may be integer or floating-point. Syntax var n=new Number(value); Examples <!DOCTYPE html>   <html>   <body>   <script>   var x=100;//integer value   var y=100.7;//floating point value   var z=12e5;//exponent value, output: 1200000   var n=new Number(20);//integer value by number object     document.write(x+" "+y+" "+z+" "+n);   </script>   </body>   </html> Try Now Output 100 100.7 1200000 20 Description The primary...

1 minute read.

Javascript If Else

Introduction The if-else statement is an important control structure for decision-making in code based on some conditions. It gives programmers the ability to add decision-making functionality into their programs. Using if-else,...

6 minutes read.

Javascript Email Validation

We can validate the email with the help of JavaScript. Here we check the condition related to any email id, like email it must have "@" and "." sign and...

2 minutes read.

Javascript Operators

The concept of operators is the basis of nearly all programming languages used in today's computing systems. Operators facilitate the execution of certain functions. For instance, the (+) symbol is...

8 minutes read.

Javascript Document Object

Document object represents the whole HTML documents. When HTML document is loaded in browser it becomes the document object. It is the root elements that represent the HTML documents. With the help of...

2 minutes read.

Javascript getElementByID

The document.getElementById() method returns the element of specified id. In below example we receive input field by using document.getElementById() method, here document.getElementById() receive input value on the basis of input field...

1 minute read.

JavaScript setInterval()

On the Window and Worker interfaces, the setInterval() method calls a function or executes a snippet with a specified time delay between each call. This function provides an interval ID that...

4 minutes read.

JavaScript radio button checked value

What are radio buttons? A radio button is defined as an icon that is used to take input from the user. The user can choose only one option(value) from the group...

5 minutes read.

Javascript Window Object

The window object represents a window in browser. An object of window is created automatically by the browser. Window is the object of browser, it is not the object of JavaScript. The...

3 minutes read.

JavaScript Console log Multiple variables

What does console.log() do in JavaScript? The console.log() is a function in JavaScript language. It is used to: Print any message in the console which is visible to the userPrint the values...

3 minutes read.