postImage

Tutorial: Javascript Loop

blogImage

By Emmanuel Chinonso

Web Developer

JavaScript Loop

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

Contrast Bootstrap UI Kit

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:

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

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:

1for (statement 1; statement 2; statement 3) {
2 // code block to be executed
3}
  • 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:

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

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:

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

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

JavaScript Code:

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

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:

1var i = 0;
2var len = cars.length;
3for (; i < len; ) {
4 text += cars[i] + '<br>';
5 i++;
6}

JavaScript For In

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

Syntax

1for (key in object) {
2 // code block to be executed
3}

JavaScript Code:

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

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

1for (variable in array) {
2 code;
3}

JavaScript Code:

1var numbers = [45, 4, 9, 16, 25];
2var txt = '';
3var x;
4for (x in numbers) {
5 txt += numbers[x] + '<br>';
6}
7document.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:

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

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:

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

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

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

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:

1let cars = ['BMW', 'Volvo', 'Mini'];
2let text = '';
3
4for (let x of cars) {
5 text += x + '<br>';
6}

Looping over a String

JavaScript Code:

1let language = 'JavaScript';
2let text = '';
3
4for (let x of language) {
5 text += x + '<br>';
6}

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

Syntax

1while (condition) {
2 // code block to be executed
3}

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:

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

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

1do {
2 // code block to be executed
3} 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:

1do {
2 text += 'The number is ' + i;
3 i++;
4} 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:

1var cars = ['BMW', 'Volvo', 'Saab', 'Ford'];
2var i = 0;
3var text = '';
4
5for (; cars[i]; ) {
6 text += cars[i] + '<br>';
7 i++;
8}

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

JavaScript Code:

1var cars = ['BMW', 'Volvo', 'Saab', 'Ford'];
2var i = 0;
3var text = '';
4while (cars[i]) {
5 text += cars[i] + '<br>';
6 i++;
7}

Contrast Bootstrap UI Kit

Create Stunning websites and web apps

Trying to build out all user interfaces and components for your website or web app from scratch can become a very tedious task. A huge reason why we created Contrast Bootstrap to help reduce the amount of time we spend doing that, so we can focus on building some other aspects of the project. Contrast Bootstrap PRO consists of a UI Kit featuring over 10000+ component variants. Together with a template of 5 admin dashboards and 23+ additional multipurpose pages template for building almost any type of website or web app. You can view a demo and learn more about Contrast by clicking here.Try contrast pro

ad-banner

Contrast Bootstrap PRO was built using the most popular CSS framework Bootstrap to help build your next landing, admin SAAS, prelaunch etc project with a clean, prebuilt and well documented template and UI components.Learn more about Contrast

Related Posts

Comments

...