JavaScript for loop is similar to the for loops in other programming languages like C, C++, and Java. The for loop takes and initial value, checks for terminating conditions, and increment the iteration as long as the continue is true.
This article we will talk about different for loop structures in JavaScript. Some of them are different from other programming languages in the sense than JavaScript also supports object-oriented programming.
Syntax – <mark style="background-color:rgba(0, 0, 0, 0);color:#a40f0f" class="has-inline-color">for </mark>
loop
The syntax for the for loop is given below. It is same as other programming languages. We will discuss about each part in a moment.
for(initial value; conditional statement ;increment value)
Initial value
The initial value is to start the first iteration which can start from either 0 or 1, whichever is required in the script. JavaScript allows you to declare variable in the place of initial value. So that you can declare a variable just for the loop. For example
for (let j = 0; j < 10; j++)
Not only integer j is declared, but also initialized with a suitable value.
Conditional Statement
The conditional statement checks if the value of loop variable results in a true or false. Therefore, output of the conditional statement is boolean and that decides whether to run the next iteration of not. The loop continues as long as the condition remains true. It will terminate the for loop when condition becomes false.
Which statement to execute?
Assume that the for loop is true and can execute the body of the loop. Then there are two possibilities to execute statements.
- execute one or more statements directly.
- or execute a block of statements enclosed within { and }.
Here is an example that shows you both the cases.
//Executes a single statement for(let i = 0;i < = 10; i++) console.log(i); //Executes a block of statements for(let j = 0; j < 10; j++) { let sum = 0; sum = sum + j; console.log(sum); }
Increment Value
The for loop is incremented by one after each iteration because the increment value is an self incrementing expression. The expression j++ is equivalent to j = j + 1. Therefore, the value of expression is self incremented after each iteration as a value of 1 is added to the previous value of variable j.
If necessary , you may change the default increment value to more than one. For example, j = j + 2 will skip one iteration after current execution. Such a structure is common in scripts.
Example #1
// This script will print numbers to the console for( let i = 1; i < = 10; i++) { console.log(i); }
The loop starts from 1 and end with printing value of 10 because i becomes 11 which is greater than condition i <= 10. Here is the output of the script.
The output shows 10 numbers printed by each iteration of the script.
The <mark style="background-color:rgba(0, 0, 0, 0);color:#a81313" class="has-inline-color">For ... In</mark>
Loop
Sometimes you need to loop through objects that have key-value pairs. The for … in loop can loop through such enumerable non-symbol properties , however, there is not guarantee that it will return values based on particular indexes. That is the reason for … in should not be used with array objects in JavaScript where index is important for each elements.Use for loop for arrays where order of access is maintained. To iterate through array object like for…in there is Array.prototype.forEach() method and for … of loop exists.
Syntax – <mark style="background-color:rgba(0, 0, 0, 0);color:#b51414" class="has-inline-color">for .. in</mark>
for ( variable in enumerable object) { statements; }
Example #2
<html> <head> <title>For ... in Loop Example<title/> <script> let fruits = {A: Banana, B: Orange, C: Pineapple, D: Mango}; for (item in fruits) { console.log(item + '=' + fruits[item]); } <script/> <head/> <body>
In the above script, the for … in check each item and get the item key and item value printed in the browser console successfully. The output of the program is given below.
Output – <mark style="background-color:rgba(0, 0, 0, 0);color:#bb1616" class="has-inline-color">for ... in</mark>
Now the key cannot be a symbol that is what non-symbolic properties mean. Suppose we change the key value of ‘Banana’ and run the loop again. It will produce and error shown below.
For-In-Loop.html:6 Uncaught SyntaxError: Unexpected token '&'
The error was generated because we tried to use an & instead of key value for “Banana”. To avoid situations like this or to use a symbol make sure you change it to string explicitly by enclosing it within quotes – “&”.
The <mark style="background-color:rgba(0, 0, 0, 0);color:#b71616" class="has-inline-color">For ... Of</mark>
Loop
The for … of loop is specially built for iterating over iterable objects such as
- Array
- String
- Array like objects such as arguments of function or NodeList from DOM tree
- TypedArray
- Map
- Set
- User-defined iterables
The for … of loop goes through list of properties ( that are values ) of an iterable object. In other words, it returns values after iteration. In the case of for..in the loop iterates the enumerable properties and not elements.To learn about iterables in detail visit JavaScript data types section.
Syntax – <mark style="background-color:rgba(0, 0, 0, 0);color:#b31010" class="has-inline-color">for ... of</mark>
loop
The syntax for the for … of loop is given below.
for ( variable of iterable object ) { statements to execute; }
The Variable
Each iteration get a different property ( values) which is assigned to the variable. It is possible to declare a variable in the loop using keywords such as let, var, and const. You may use this variable to manipulate the values successfully.
Iterable object
The iterable objects are special type of objects that define iteration behavior used in for .. of loop. They all implement a method called Symbol.iterable. The JavaScript built-in objects like array, strings uses this Symbol.iterable by default.
Example #3
<html> <head> <title>For ... Of Loop Example<title/> <script> let iterable_numbers = [23, 44, 53, 66]; for (const val of iterable_numbers) { console.log(val); } <script/> <head/> <body> <h2>For .. Of Example<h2/> <body/> <html/>
The for .. of loop iterates over each element of the array and display it.
Output – <mark style="background-color:rgba(0, 0, 0, 0);color:#b31818" class="has-inline-color">for .. of</mark>
The <mark style="background-color:rgba(0, 0, 0, 0);color:#a80f0f" class="has-inline-color">Array.Prototype.forEach ( )</mark>
Method
The forEach () method is of class array and help to iterate over each element of the array. This method needs a function that can access to the currentvalue, array index, and the array object. The index and the array object are optional.
Syntax – <mark style="background-color:rgba(0, 0, 0, 0);color:#b50a0a" class="has-inline-color">forEach ()</mark>
array.forEach(function(currentvalue,index, arr), thisvalue));
Example #4
In this example, you will execute a print function for each element of an array. The function has access to the current value , the array index, and the array object. The function can access one or more parameters as per the requirement.
<!DOCTYPE html> <html> <head> <title>forEach ( ) Loop Example<title/> <script> //First you must declare the array num = [4,5,6,88]; //Next use the for-each loop num.forEach(print); //Now declare this function name function print(item, index) { console.log(item, index); } <script/> <head/> <body> <h3> forEach ( ) Loop Example<h2/> <body/> <html/>
The function will take two parameters for each element in the array and then print them to the console. Here is the output from the function.
Function Variable
If you only want to access a single element then you can write a shortcut function and print that element using forEach() loop.
Example #5
<!DOCTYPE html> <html> <head> <title>forEach ( ) Shortcut<title/> <script> // declare the array first array = [23, 354, 32, 251 ];; // now use the for-each loop array.forEach(print => console.log(print)); <script/> <head/> <body> <h3> forEach ( ) Shortcut<h2/> <body/> <html/>
Output – <mark style="background-color:rgba(0, 0, 0, 0);color:#af0d0d" class="has-inline-color">forEach( ) </mark>
Shortcut
there is no need to define the print function which is the function variable now and the function will print each element from the right.
A function variable is a small function or shortcut function. You will learn more about function in JavaScript function section. Note that the function variable print access only one parameter – the currentvalue.
References
- Javascript.info. 2020. Iterables. [online] Available at: <https://javascript.info/iterable> [Accessed 27 August 2020].
- W3schools.com. 2020. Javascript Array Foreach() Method. [online] Available at:<https://www.w3schools.com/jsref/jsref_foreach.asp> [Accessed 27 August 2020].
- MDN Web Docs. 2020. For…In. [online] Available at: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for…in> [Accessed 27 August 2020].
- Powers, S., 2010. Javascript Cookbook. 1st ed. Farnham: O’Reilly.