Tutorial: Javascript Loop
Tags: javascript, webdev, programming, codenewbie
Published: 2022-01-28 07:41:36

---
title: Tutorial: Javascript Loop
published: true
date: 2021-01-10 01:16:04 UTC
tags: [javascript, webdev, programming, codenewbie]
canonical_url: https://www.devwares.com/blog//javascript-for-loop
---

## JavaScript Loop

JavaScript Loop is used to execute a section of code many times


**JavaScript Loops:** Loops are useful if you want to run the same code multiple times, each time with a new value. When working with arrays, this is frequently the case:

**Instead of writing:**

- text += cars[0] + `<br>`;
- text += cars[1] + `<br>`;
- text += cars[2] + `<br>`;
- text += cars[3] + `<br>`;
- text += cars[4] + `<br>`;
- text += cars[5] + `<br>`;

**You can write:**

**JavaScript Code:**

```javascript
var i;
for (i = 0; i < cars.length; i++) {
  text += cars[i] + '<br>';
}

```

**Different Kinds of Loops**

JavaScript provides various types of loops:

- for - loops over a block of code several times.
- for/in - loops over an object's properties
- for/of - loops through an iterable object's values
- while - cycles through a piece of code as long as a stated condition is true.
- do/while - loops through a piece of code while a particular condition is true.

**The For Loop** The syntax for the for loop is as follows:

```
for (statement 1; statement 2; statement 3) {
  // code block to be executed
}

```

- Statement 1 is executed (once) before the code block is executed.
- Statement 2 specifies the circumstance under which the code block will be executed.
- After the code block has been performed, Statement 3 is executed (every time).

**JavaScript Code:**

```javascript
for (i = 0; i < 5; i++) {
  text += 'The number is ' + i + '<br>';
}

```

**From the code above, you can read:**

- Statement 1 initializes a variable (var i = 0) before the loop begins.
- Statement 2 specifies the condition under which the loop will run (i must be less than 5).
- Statement 3 increments a value (i++) each time the loop's function is executed.

**Statement 1**

Statement 1 is normally used to initialize the variable used in the loop (i = 0). This is not always the case, and JavaScript is unconcerned about it. Statement 1 is not required. In statement 1, you can start numerous values (separated by a comma):

**JavaScript Code:**

```javascript
for (i = 0, len = cars.length, text = ''; i < len; i++) {
  text += cars[i] + '<br>';
}

```

You can also omit statement 1 (for example, if your values are already set before the loop begins):

**JavaScript Code:**

```javascript
var i = 2;
var len = cars.length;
var text = '';
for (; i < len; i++) {
  text += cars[i] + '<br>';
}

```

**Statement 2**

Statement 2 is frequently used to assess the condition of the initial variable. This is not always the case, and JavaScript is unconcerned about it. Statement 2 is optional as well. If statement 2 returns true, the loop will be restarted; if it returns false, the loop will be terminated. If statement 2 is omitted, a break must be provided within the loop. Otherwise, the cycle will never come to an end. This will cause your browser to crash. Breaks are covered in a subsequent chapter of this lesson. Statement 3 Statement 3 frequently increases the value of the initial variable. This is not necessarily true, JavaScript is unconcerned, and statement 3 is optional. Statement 3 can do any operation, such as a negative increment (i—), a positive increment i = i + 15), or nothing at all. Statement 3 can alternatively be omitted (as when incrementing numbers within the loop):

**JavaScript Code:**

```javascript
var i = 0;
var len = cars.length;
for (; i < len; ) {
  text += cars[i] + '<br>';
  i++;
}

```

**JavaScript For In**

The For/In Loop: The for/in statement in JavaScript runs through the properties of an Object:

**Syntax**

```
for (key in object) {
  // code block to be executed
}

```

**JavaScript Code:**

```javascript
var person = { fname: 'John', lname: 'Doe', age: 25 };
var text = '';
var x;
for (x in person) {
  text += person[x];
}

```

**Code Explained**

- The for in loop iterates over a person object
- Each iteration returns a key (x)
- The key is used to access the value of the key
- person[x] represents the value of the key.

**For/In Over Arrays:** The JavaScript for/in statement can also loop over the properties of an Array:

**Syntax**

```
for (variable in array) {
  code;
}

```

**JavaScript Code:**

```javascript
var numbers = [45, 4, 9, 16, 25];
var txt = '';
var x;
for (x in numbers) {
  txt += numbers[x] + '<br>';
}
document.getElementById('demo').innerHTML = txt;

```

If the order of the indexes is crucial, do not use for in over an Array. Because index order is implementation-dependent, array values may not be retrieved in the expected order. When the order is crucial, use a for loop, a for of loop, or Array.forEach().

**Array.forEach():**For each array element, the forEach() method calls a function (a callback function).

**JavaScript Code:**

```javascript
var txt = '';
var numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);
function myFunction(value, index, array) {
  txt = txt + value + '<br>';
}

```

The function takes 3 arguments:

- The item value
- The item index
- The array itself

The example above uses only the value parameter. The example can be rewritten to:

**JavaScript Code:**

```javascript
var txt = '';
var numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);
function myFunction(value) {
  txt = txt + value + '<br>';
}

```

The For/Of Loop The for/of statement loops through the values of an iterable object in JavaScript. It allows you to loop over iterable data structures like Arrays, Strings, Maps, NodeLists, and others:

**Syntax**

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

```

The for/of statement loops through the values of an iterable object in JavaScript. It allows you to loop over iterable data structures like Arrays, Strings, Maps, NodeLists, and others:

iterable - An object whose properties can be iterated.

**Looping over an Array**

**JavaScript Code:**

```javascript
let cars = ['BMW', 'Volvo', 'Mini'];
let text = '';

for (let x of cars) {
  text += x + '<br>';
}

```

**Looping over a String**

**JavaScript Code:**

```javascript
let language = 'JavaScript';
let text = '';

for (let x of language) {
  text += x + '<br>';
}

```

**The While Loop:** The while loop repeats a section of code as long as a defined condition is true.

**Syntax**

```
while (condition) {
  // code block to be executed
}

```

The code in the loop in the following JavaScript code will be executed repeatedly as long as a variable I is less than 10:

**JavaScript Code:**

```javascript
while (i < 10) {
  text += 'The number is ' + i;
  i++;
}

```

The loop will never terminate if you forget to raise the variable used in the condition. This will cause your browser to crash.

**The Do/While Loop** The do/while loop is an alternative to the while loop. This loop will execute the code block once before checking to see if the condition is true, and then it will loop as long as the condition is true.

**Syntax**

```
do {
  // code block to be executed
} while (condition);

```

The do/while loop is used in the JavaScript code below. Because the code block is run before the condition is tested, the loop will always be executed at least once, even if the condition is false:

**JavaScript Code:**

```javascript
do {
  text += 'The number is ' + i;
  i++;
} while (i < 10);

```

If you don't raise the variable used in the condition, the loop will never stop!

**Comparing For and While**

If you studied the preceding chapter about the for loop, you will notice that a while loop is quite similar to a for loop, with the exception of statements 1 and 3. The for loop in this code is used to collect the automobile names from the cars array

**JavaScript Code:**

```javascript
var cars = ['BMW', 'Volvo', 'Saab', 'Ford'];
var i = 0;
var text = '';

for (; cars[i]; ) {
  text += cars[i] + '<br>';
  i++;
}

```

The loop in this code uses a while loop to collect the car names from the cars array:

**JavaScript Code:**

```javascript
var cars = ['BMW', 'Volvo', 'Saab', 'Ford'];
var i = 0;
var text = '';
while (cars[i]) {
  text += cars[i] + '<br>';
  i++;
}

```

[![Contrast Bootstrap UI Kit](https://www.devwares.com/static/6b149e3d75b230f7e8452ace9e21bb05/587b0/banner-ad-1.png "Contrast Bootstrap UI Kit")](https://www.devwares.com/product/bootstrap-contrast-pro)


## Resources

You may find the following resources useful:

- [Get Contrast PRO](https://www.devwares.com/product/contrast-pro)
- [How to create a beautiful React Bootstrap progress bar](https://www.devwares.com/blog/create-progress-with-contrast)
- [HTML Quotations and comments](https://www.devwares.com/blog/html-quotations)
- [How to create a beautiful Bootstrap stepper](https://www.devwares.com/blog/create-stepper-with-contrast)
- [Tutorial: Javascript Events](https://www.devwares.com/blog/javascript-events)

- [Contrast Installation](https://www.devwares.com/docs/contrast/react/Installation/)
- [Charts](https://www.devwares.com/docs/contrast/react/chart/)
- [Accordion](https://www.devwares.com/docs/contrast/react/components/accordion/)
- [Alert](https://www.devwares.com/docs/contrast/react/components/alert/)
- [Animation](https://www.devwares.com/docs/contrast/react/components/animations/)
- [Autocomplete](https://www.devwares.com/docs/contrast/react/components/autocomplete/)
- [Badges](https://www.devwares.com/docs/contrast/react/components/badge/)
- [Box](https://www.devwares.com/docs/contrast/react/components/box/)
- [Breadcrumb](https://www.devwares.com/docs/contrast/react/components/breadcrumb/)
- [ButtonGroup](https://www.devwares.com/docs/contrast/react/components/buttonGroup/)
- [ButtonToolbar](https://www.devwares.com/docs/contrast/react/components/buttonToolbar/)
- [Button](https://www.devwares.com/docs/contrast/react/components/buttons/)
- [Card](https://www.devwares.com/docs/contrast/react/components/card/)
- [Carousel](https://www.devwares.com/docs/contrast/react/components/carousel/)
- [Checkbox](https://www.devwares.com/docs/contrast/react/components/checkbox/)
- [Collapse](https://www.devwares.com/docs/contrast/react/components/collapse/)
- [DropDown](https://www.devwares.com/docs/contrast/react/components/dropdown/)
- [Footer](https://www.devwares.com/docs/contrast/react/components/footer/)
- [Icon](https://www.devwares.com/docs/contrast/react/components/icon/)
- [Iframe](https://www.devwares.com/docs/contrast/react/components/iframe/)
- [Input](https://www.devwares.com/docs/contrast/react/components/input/)
- [InputGroup](https://www.devwares.com/docs/contrast/react/components/inputgroup/)
- [ListGroup](https://www.devwares.com/docs/contrast/react/components/listgroup/)
- [Mask](https://www.devwares.com/docs/contrast/react/components/mask/)
- [Modal](https://www.devwares.com/docs/contrast/react/components/modal/)
- [Multiselect](https://www.devwares.com/docs/contrast/react/components/multiselect/)
- [Notification](https://www.devwares.com/docs/contrast/react/components/notification/)
- [Pane](https://www.devwares.com/docs/contrast/react/components/pane/)
- [Panel](https://www.devwares.com/docs/contrast/react/components/panels/)
- [Progress](https://www.devwares.com/docs/contrast/react/components/progress/)
- [Radio](https://www.devwares.com/docs/contrast/react/components/radio/)
- [Rating](https://www.devwares.com/docs/contrast/react/components/rating/)
- [Select](https://www.devwares.com/docs/contrast/react/components/select/)
- [Select 2](https://www.devwares.com/docs/contrast/react/components/select2/)
- [SmoothScroll](https://www.devwares.com/docs/contrast/react/components/smoothscroll/)
- [Slider](https://www.devwares.com/docs/contrast/react/components/slider/)
- [Spinner](https://www.devwares.com/docs/contrast/react/components/spinner/)
- [Stepper](https://www.devwares.com/docs/contrast/react/components/stepper/)
- [Switch](https://www.devwares.com/docs/contrast/react/components/switch/)
- [Navbar](https://www.devwares.com/docs/contrast/react/navigation/navbar/)
- [Pagination](https://www.devwares.com/docs/contrast/react/navigation/pagination/)
- [Sidebar](https://www.devwares.com/docs/contrast/react/navigation/sidebar/)
- [Tab](https://www.devwares.com/docs/contrast/react/navigation/tabs/)
- [Date Picker](https://www.devwares.com/docs/contrast/react/sections/datepicker/)
- [FileUploader](https://www.devwares.com/docs/contrast/react/sections/fileuploader/)
- [Time Picker](https://www.devwares.com/docs/contrast/react/sections/timepicker/)
- [Editable Table](https://www.devwares.com/docs/contrast/react/table/editabletable/)
- [Table](https://www.devwares.com/docs/contrast/react/table/table/)
- [Data Table](https://www.devwares.com/docs/contrast/react/table/datatables/)
- [Widgets]
(https://www.devwares.com/docs/contrast/react/widgets/)
- [Forms]
(https://www.devwares.com/docs/contrast/react/forms/)