DEV Community

Sampson Ovuoba for Devwares

Posted on • Originally published at devwares.com on

Tutorial: Javascript 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:

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

Enter fullscreen mode Exit fullscreen mode

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
}

Enter fullscreen mode Exit fullscreen mode
  • 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:

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

Enter fullscreen mode Exit fullscreen mode

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:

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

Enter fullscreen mode Exit fullscreen mode

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

JavaScript Code:

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

Enter fullscreen mode Exit fullscreen mode

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:

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

Enter fullscreen mode Exit fullscreen mode

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
}

Enter fullscreen mode Exit fullscreen mode

JavaScript Code:

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

Enter fullscreen mode Exit fullscreen mode

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;
}

Enter fullscreen mode Exit fullscreen mode

JavaScript Code:

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

Enter fullscreen mode Exit fullscreen mode

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:

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

Enter fullscreen mode Exit fullscreen mode

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:

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

Enter fullscreen mode Exit fullscreen mode

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
}

Enter fullscreen mode Exit fullscreen mode

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:

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

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

Enter fullscreen mode Exit fullscreen mode

Looping over a String

JavaScript Code:

let language = 'JavaScript';
let text = '';

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

Enter fullscreen mode Exit fullscreen mode

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
}

Enter fullscreen mode Exit fullscreen mode

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:

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

Enter fullscreen mode Exit fullscreen mode

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);

Enter fullscreen mode Exit fullscreen mode

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:

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

Enter fullscreen mode Exit fullscreen mode

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:

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

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

Enter fullscreen mode Exit fullscreen mode

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

JavaScript Code:

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

Enter fullscreen mode Exit fullscreen mode

Contrast Bootstrap UI Kit

Resources

You may find the following resources useful:

Top comments (0)