{"id":1982,"date":"2018-07-25T15:31:02","date_gmt":"2018-07-25T15:31:02","guid":{"rendered":"https:\/\/tinjurewp.com\/jsblog\/?p=1982"},"modified":"2018-07-25T15:31:02","modified_gmt":"2018-07-25T15:31:02","slug":"understanding-javascript-for-loops","status":"publish","type":"post","link":"https:\/\/learncode.tinjurewp.com\/understanding-javascript-for-loops\/","title":{"rendered":"Understanding JavaScript For Loops"},"content":{"rendered":"<p><code><\/code><\/p>\n<p class=\"note icon-note\"><strong>Note<\/strong>: This post is work-in-progress learning-note and still in active development and updated regularly.<\/p>\n<p>In JS programming, like in other programming languages, there would be a need to do certain task repeatedly, for example to run a block of code to perform repetitive tasks. <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Guide\/Loops_and_iteration\" target=\"_blank\" rel=\"noopener\">JS loops<\/a> offer easy way to perform same task repetitively. There are different kinds of loops but all do same thing: repeat certain actions for a number of times.<\/p>\n<p>The <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Guide\/Loops_and_iteration\" target=\"_blank\" rel=\"noopener\">MDN Document<\/a> list different kinds of <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Guide\/Loops_and_iteration\" target=\"_blank\" rel=\"noopener\">Loops &amp; Iterations<\/a>. In our previous learning post we discussed <a href=\"https:\/\/tinjurewp.com\/jsblog\/understanding-javascript-conditional-statements\/\" target=\"_blank\" rel=\"noopener\">Conditional Statements<\/a> to perform certain tasks repeatedly based on <code>true<\/code> or <code>false<\/code> return of specified conditions.\u00a0 While the conditional statements are run only once, the <code>while<\/code> and <code>do..while<\/code> loop execute multiple times as long as the conditions evaluates <code>true<\/code>. In our previous learning-note post: <a href=\"https:\/\/tinjurewp.com\/jsblog\/learning-javascript-while-and-do-while-loops\" target=\"_blank\" rel=\"noopener\">Learning JavaScript While and Do..While Loops<\/a>, we discussed <code>while<\/code> and <code>do..while<\/code> statements with some use case examples, together with using the <code>break\/continue<\/code>, and <code>label<\/code> statements.<\/p>\n<p>In this post, other common types of JS loops:the <code>for<\/code> statement, including the <code>for..in<\/code> and <code>for..of<\/code> statements will be discussed with some use case examples.<\/p>\n<h3>The For Statement<\/h3>\n<p>The <code>for<\/code> statement is fundamental to JS programming. To quote from the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/for\" target=\"_blank\" rel=\"noopener\">MDN<\/a> &#8211; &#8220;<em>the <strong>for statement<\/strong> creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/block\">block statement<\/a>) to be executed in the loop<\/em>&#8220;.<\/p>\n<h5>Basic Syntax<\/h5>\n<p>A <code>for<\/code> loop executes a task multiple times until a specified condition is evaluated <code>false<\/code>.<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/basic syntax\nfor (initialization; condition; incrementExpression) {\n   statement; \/\/code block\n   ..\n}<\/code><\/pre>\n<p>The <code>for<\/code> statement syntax consists of the following three <em>expressions<\/em>:<\/p>\n<ul>\n<li><strong>Initialization<\/strong>: It is an expression that is typically used to initialize a loop counter variable. This expression can also be used to declare new variables with <code>var<\/code>, <code>let<\/code> or <code>const<\/code> keyword.<\/li>\n<li><strong>Condition<\/strong>: It is an expression to be evaluated before each loop iteration. If this expression is evaluated <code>true<\/code> statement block (body of code) is executed. If the condition returns <code>false<\/code>, statements are not executed and loop terminates. If the conditions are omitted, it is evaluated as <code>true<\/code>.<\/li>\n<li><strong>Statement<\/strong>: The statement (body of code) to be executed when the condition returns <code>true<\/code>. If a loop has multiple statements, then they must be enclosed within <code>({ ..})<\/code> as block statement. If there are no statements within a loop, an <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/Empty\" target=\"_blank\" rel=\"noopener\">empty<\/a> statement (<code>;<\/code>) is used.<\/li>\n<li><strong>Increment Expression<\/strong>: This is also known as <em>final expression<\/em>, which is executed at the end of each iteration. This is generally used to update or increment the counter variable. This step occurs before the next evaluation of the <code>condition<\/code>.<\/li>\n<\/ul>\n<h6>Example<\/h6>\n<p>Lets understand these expression using a simple example:<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/initialize for statement with 4 iterations\nfor (let i = 0; i &lt; 3; i++) {\n \/\/print each iteration to the console\n  console.log(i); \n}\n\/\/OUTPUT\n0\n1\n2<\/code><\/pre>\n<p>In the example above, the <code>for<\/code> loop initialized with <code>let i = 0<\/code> (<em>initialization<\/em> step) meaning the loop starts at <code>0<\/code>. The loop <em>condition<\/em> statement is defined as <code>i &lt; 3<\/code>, meaning that as long as <code>i<\/code> is less than <code>3<\/code> the loop executes &#8211; prints the value of <code>i<\/code> to the console (line 4). The final or <em>increment<\/em> expression <code>i++<\/code> runs after each pass through the loop. The console prints out (line 7-9) starting <code>0<\/code> and terminates when <code>i<\/code> equals <code>3<\/code> but NOT including the value of <code>3<\/code>.<\/p>\n<table class=\"leanjs\">\n<thead>\n<tr>\n<th>Step<\/th>\n<th>Expression<\/th>\n<th>Description<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>initialization<\/td>\n<td><code>i = 0<\/code><\/td>\n<td>Executes once upon entering the loop.<\/td>\n<\/tr>\n<tr>\n<td>condition<\/td>\n<td><code>i &lt; 3<\/code><\/td>\n<td>Checked before every loop iteration, if <code>false<\/code> the loop terminates.<\/td>\n<\/tr>\n<tr>\n<td>increment<\/td>\n<td><code>i++<\/code><\/td>\n<td>Executes after the statement block\u00a0 on each iteration, but before the condition check.<\/td>\n<\/tr>\n<tr>\n<td>statement<\/td>\n<td><code>console.log(i)<\/code><\/td>\n<td>Runs again and again while the condition is <code>true<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>The above table (adopted from <a href=\"https:\/\/javascript.info\/while-for\" target=\"_blank\" rel=\"noopener\">The Modern JavaScript Tutorial<\/a>) illustrates each step, expression and action in a typical loop iteration.<\/p>\n<h4>Understanding Expression Parameters<\/h4>\n<h5>Initialization<\/h5>\n<p>This is the first expression in a loop and it is essential to begin a loop with initialization expression. A variable is declared and\/or initialized at this step.<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/initialize var outside loop\nlet i = 0;\n\/\/initilialize within a loop\nfor(i = 0; condition; incrementExpression) {\n   statements;\n   ..\n}<\/code><\/pre>\n<p>In the example above, variable <code>i<\/code> is declared with <code>let<\/code> keyword and assigned a value of <code>0<\/code>. Most commonly used variable name in such a <code>for<\/code> loop is <code>i<\/code> (which means iteration) but it can be anything, for example <code>a<\/code> or <code>x<\/code> etc.<\/p>\n<p>This variable is also known as counter variable, can be declared right in the loop, a process called \u201c<strong>inline<\/strong>\u201d as well as outside the loop (line 1). The inline declared variables are visible only inside the loop. Lets examine this process below with an example.<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/inline assignment expression\nfor (let i = 0; i &lt; 3; i++) {\n  console.log(i); \/\/ =&gt; 0, 1, 2\n}\nconsole.log(i); \/\/ =&gt;ReferenceError: i is not defined\n\n\/\/initialize var outside the loop\nlet i = 0;\n\/\/use existing var\nfor (i = 0; i &lt; 3; i++) {\n  console.log(i); \/\/ =&gt; 0, 1, 2\n}\nconsole.log(i); \/\/ =&gt; 3<\/code><\/pre>\n<p>In the example above (adopted from <a href=\"https:\/\/javascript.info\/while-for#the-for-loop\" target=\"_blank\" rel=\"noopener\">The Modern JavaScript Tutoria<\/a>l), the <code>i<\/code> variable is declared and assigned a value of <code>0<\/code> right in the loop (line 2). Such <em>inline<\/em> variables are visible inside the loop only (line 3), when accessed from outside the loop, it throws a var not defined <code>ReferenceError<\/code> (line 5).<\/p>\n<p>On the other hand, if <code>var<\/code> is declared outside the loop, value of <code>i<\/code> can be accessed outside of the loop as shown in line 8-13. In this example, var <code>i<\/code> is declared outside the loop (line 8) and value of <code>i<\/code> is assigned to <code>0<\/code> inside the <code>for<\/code> loop (line 10). Now, with the same condition, increment and loop body statement (lines: 10-11), value of <code>i<\/code> can be accessible from outside the loop, because the variable was declared outside the loop.<\/p>\n<h5>Condition<\/h5>\n<p>The condition expression evaluates <code>true<\/code> or <code>false<\/code>. As long as the condition returns <code>true<\/code>, statement block is executed. Once the condition is evaluated <code>false<\/code>, execution terminates and moves to next part of the code.<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/initialize var \nlet i = 0;\n\/\/define loop condition\nfor(i = 0; i &lt; 3; incrementExpression) {\n   statements;\n   ..\n}<\/code><\/pre>\n<p>Continuing our earlier example, where var <code>i<\/code> was initialized to <code>0<\/code>.\u00a0 Here a condition for executing the loop is set as <code>i &lt; 3 <\/code>which means that as long as value of <code>i<\/code> is less than <code>3<\/code> (excluding <code>3<\/code>), the condition returns <code>true<\/code>. When its value is <code>3<\/code> or more the condition evaluates <code>false<\/code> and execution of loop statement terminates.<\/p>\n<h5>Increment Expression<\/h5>\n<p>The <em>increment Expression<\/em> is run after each iteration. This is often used to increase or decrease the value of variable <em>i.e.<\/em> <code>i<\/code> in our example. Revisiting our earlier example, lets increase the the value of <code>i<\/code> by one as shown below:<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/initialize var \nlet i = 0;\n\/\/define loop condition\nfor(i = 0; i &lt; 3; i++) {\n   statements;\n   ..\n}<\/code><\/pre>\n<p>In the example above, the <em>initialization<\/em> and <em>condition<\/em> blocks are initialized previously. To increase the value <code>i<\/code> by one, it looks like <code>i + 1<\/code> with <code>i = i + 1<\/code>. Its shorthand form is <code>i++<\/code>,\u00a0 which is commonly used in most <code>for<\/code> loops.<\/p>\n<p>For example, if we wanted to decrease the value of <code>i<\/code> by one after each iteration, it becomes <code>i-1<\/code> with <code>i = i - 1<\/code>. Just like in increment, its shorthand form is <code>i--<\/code>, which is also the commonly used form in the <code>for<\/code> loops.<\/p>\n<h5>Statement<\/h5>\n<p>The <em>statement<\/em> or the body of code is executed when the condition expression returns <code>true<\/code>.<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/initialize var outside the loop\nlet i = 0;\n\/\/use existing var\nfor (i = 0; i &lt; 3; i++) {\n  \/\/ to print value of to the console\n  console.log(i); \n}\n\/\/OUTPUT\n0\n1\n2<\/code><\/pre>\n<p>In the example above, a simple statement to print the value of <code>i<\/code> to the console\u00a0 after each iteration (line 5) is added. This completes our simple <code>for<\/code> loop example.<\/p>\n<p>Briefly summarizing again,\u00a0 first value of <code>i<\/code> is set to <code>0<\/code> (<em>initialization<\/em> block). Next we set a condition for loop iteration i.e. to run until <code>i<\/code> is less than <code>3<\/code> (<em>condition<\/em> block). Finally, value of <code>i<\/code> was increased by one after each iteration (<em>increment<\/em> block). The statement block prints value of <code>i<\/code> to the console (<em>statement<\/em> block) as shown in the output (lines: 9-11).<\/p>\n<h5>Optional \u2018for\u2019 Expressions<\/h5>\n<p>All the three expressions of the <code>for<\/code> statement loop are optional.<\/p>\n<p><strong>1. <em>Initialization<\/em> block can be optional<\/strong><br \/>\nThe <em>initialization<\/em> expression in our <code>for<\/code> loop example can be omitted by initializing the <code>var<\/code> outside the loop (line 2).<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/initialize var outside the loop\nlet i = 0;\n\/\/initialize loop with existing var\nfor (; i &lt; 3; i++) {\n  \/\/ to print value of to the console\n  console.log(i); \/\/ =&gt; 0, 1, 2\n}<\/code><\/pre>\n<p>Take a note that even though the var <code>i<\/code> <em>initialization<\/em> block may not be required in a <code>for<\/code> loop, a semicolon <code>;<\/code> is required (line 2).<\/p>\n<p><strong>2. Condition block can be optional<\/strong><br \/>\nLike in the <em>initialization<\/em> block, the <em>condition<\/em> block is also optional and can be omitted from the <code>for<\/code> loop as shown below.<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/initialize var outside the loop\nlet i = 0;\n\/\/omit initialization &amp; condition\nfor (; ; i++) {\n \/\/ must include break statement\n if (i &gt; 2) { \/\/condition for break\n    break; \/\/ must be included\n }\n  \/\/ to print value of to the console\n  console.log(i); \/\/=&gt; 0, 1, 2\n}<\/code><\/pre>\n<p>Using the same previous example, the <em>condition<\/em> block is removed from our <code>for<\/code> loop example (line 4). But the loop to work, <code>if<\/code> statement MUST be combined with <code>break<\/code> statement to reverse the condition ( <code>i &gt; 2<\/code>) of <code>for<\/code> loop &#8211; to terminate loop iteration if <code>i<\/code> is greater than <code>2<\/code> (a reverse of <code>true<\/code> condition).<\/p>\n<p class=\"warning icon-warning\"><strong>Warning<\/strong>: The conditional statement MUST be followed by the <code>break<\/code> statement<em>,<\/em> otherwise the loop runs forever like in an <em>infinite loop<\/em> and crashing the browser.<\/p>\n<p><strong>3. Initialization block can be optional<\/strong><br \/>\nJust like in <em>initialization<\/em> and <em>condition<\/em> blocks, the <em>incremental<\/em> block can also be removed but the loop to work, it should be added at the end of the <code>for<\/code> loop (line 11).<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/initialize var outside the loop\nlet i = 0;\n\/\/omit all expression\nfor (; ; ) {\n \/\/ must include break statement\n if (i &gt; 2) { \/\/break condition\n    break; \/\/ MUST be included\n }\n  \/\/ to print value of to the console\n  console.log(i); \/\/=&gt; 0, 1, 2\n  i++;\n}<\/code><\/pre>\n<p>In the example above, the <em>increment<\/em> expression is removed from the <code>for<\/code> loop (line 4) but both the semicolon (\u00a0<code>; ;<\/code> ) must be included to execute the loop. Just like in the <em>condition<\/em> block <code>break<\/code> statement MUST be included so that the condition expresion for <code>break<\/code> statement returns <code>true<\/code> at some point.<\/p>\n<h3>The &#8216;for..in&#8217; Statement<\/h3>\n<p>An object contains <em>enumerable<\/em> property where <code>for..in<\/code> is used to <em>iterate<\/em> over enumerable property of an object. In a previous learning-post <a href=\"https:\/\/tinjurewp.com\/jsblog\/javascripts-objects-the-basics\/\" target=\"_blank\" rel=\"noopener\">JavaScript Objects &#8211; The Basics<\/a>, use of <code>for..in<\/code> iteration in an object was\u00a0 discussed briefly. Enumerable properties show up in <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/for...in\" target=\"_blank\" rel=\"noopener\">for\u2026in<\/a> loops (once <code>for each<\/code> property) unless the property\u2019s name is\u00a0<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Symbol\" target=\"_blank\" rel=\"noopener\">Symbol<\/a>. A more detail discussion on enumeration is covered in a separate learning-note post &#8211; <a href=\"https:\/\/tinjurewp.com\/jsblog\/understanding-enumerable-properties-in-javascript\/\" target=\"_blank\" rel=\"noopener\">Understanding Enumerable Properties in JavaScript<\/a>.<\/p>\n<h6>Basic Syntax<\/h6>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/basic syntax\nfor (variable in object) { \n   statement;\n}<\/code><\/pre>\n<p>The <code>for..in<\/code> syntax takes following two expressions:<\/p>\n<ul>\n<li><strong>variable<\/strong>: A different property name is assigned to <em>variable<\/em> on each iteration.<\/li>\n<li><strong>object<\/strong>: Object whose non-Symbol enumerable properties are iterated.<\/li>\n<\/ul>\n<h6>Iterating Over Objects<\/h6>\n<p>Using the <code>for..in<\/code> statement, <em>key<\/em> and <em>values<\/em> of an object can be iterated in most straightforward way. A very basic use case example of <code>for..in<\/code> loop shown below iterates over the properties of an object (<em>keys<\/em> &amp; <em>values<\/em>).<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/initialize myCar object\nlet myCar = { make: &#039;Toyota&#039;, model: &#039;Corolla&#039;, year: &#039;2017&#039;\n};\n\n\/\/iterate keys with for..in \nfor (let key in myCar) { \n   console.log(key); \/\/ print object keys\n }\n\/\/OUTPUT\nmake\nmodel\nyear\n\n\/\/iterate keys with for..in\nfor (let value in myCar) {\n  console.log(myCar[value]); \/\/ print object values\n}\n\/\/OUTPUT\nToyota \nCorolla \n2017\n\n\/\/iterate keys with for..in\nfor (let key in myCar) {\n  \/\/print object keys &amp; values\n  console.log(`${key} : ${myCar[key]}`);\n}\n\/\/OUTPUT\nmake : Toyota \nmodel : Corolla \nyear : 2017<\/code><\/pre>\n<p>In the example above, a simple <code>myCar<\/code> object is created with three <em>name:value<\/em> pairs (line 2). Using <code>for..in<\/code> iteration (lines 6) <em>keys<\/em> (name) of object items can be accessed (lines: 10-12).<\/p>\n<p>Likewise, <em>values<\/em> of each item can be accessed as the index value of the <code>myCar<\/code> object (lines: 19-21). Both the <em>key<\/em> and <em>values<\/em> of <code>myCar<\/code> object can be accessed to the console (lines: 29-31).<\/p>\n<h6>Iterating Over Arrays<\/h6>\n<p>In an array, the <em>key<\/em> for value are numerical indexes. Just like in an object, these indexes are enumerable properties and thus <code>for..in<\/code> statement can be used to iterate over arrays.<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/initiize myArray\nlet myArray = [20, 25, 30];\n\/\/iterating over with for..in\nfor (const x in myArray) {\n  console.log(myArray[x]);\n}\n\/\/OUTPUT\n20\n25\n30<\/code><\/pre>\n<p class=\"tip icon-alert\"><strong>Alert<\/strong>. It is a general practice not to use <code>for..in<\/code> statement to iterate over arrays.<\/p>\n<h6>Iterating Over String<\/h6>\n<p>Since each character in a string has an index, which are enumerable properties too, and can be iterated using the <code>for..in<\/code> statement, as shown below:<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/initializing myString\nlet myString = &quot;TOYOTA&quot;;\n\/\/Iterating over with for..in\nfor (const x in myString) {\n  console.log(myString[x]);\n}\n\/\/OUTPUT\nT\nO\nY\nO\nT\nA<\/code><\/pre>\n<p class=\"tip icon-alert\"><strong>Alert<\/strong>. It is a general practice not to use <code>for..in<\/code> statement to iterate over strings.<\/p>\n<h3>The &#8216;for..of&#8217; Statement<\/h3>\n<p>The <code>for..in<\/code> statement method described in previous section is useful for iterating over object properties. The ES6 introduced <code>for..of<\/code> statement is used to iterate over <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/String\" target=\"_blank\" rel=\"noopener\">strings<\/a> and <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Array\" target=\"_blank\" rel=\"noopener\">arrays<\/a>.<\/p>\n<p>To quote from the MDN Documentation: \u201cT<em>he <a title=\"The for...of statement creates a loop iterating over iterable objects (including the built-in String, Array, e.g. the Array-like arguments or\u00a0NodeList objects, TypedArray, Map and Set, and user-defined iterables), invoking a custom iteration hook with statements to be executed for the value of each distinct property of the object.\" href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/statements\/for...of\"><code>for...of<\/code><\/a> statement creates a loop Iterating over <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Guide\/iterable\">iterable objects<\/a>(including <a title=\"The JavaScript Array\u00a0object is a global object that\u00a0is used in the\u00a0construction\u00a0of\u00a0arrays; which are high-level, list-like objects.\" href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Array\"><code>Array<\/code><\/a>,\u00a0<a title=\"The Map object holds key-value pairs.\" href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Map\"><code>Map<\/code><\/a>, <a title=\"The Set object lets you store unique values of any type, whether primitive values or object references.\" href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Set\"><code>Set<\/code><\/a>, <a title=\"The arguments object is an Array-like object corresponding to the arguments passed to a function.\" href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/functions\/arguments\"><code>arguments<\/code><\/a> object and so on), invoking a custom iteration hook with statements to be executed for the value of each distinct property<\/em>\u201c.<\/p>\n<p>The <code>for..of<\/code> statement is a newer method and was introduced in ECMAScript 6 (ES6) to iterate over &#8220;<em>iterable collections<\/em>&#8220;. This is commonly used to iterate over objects like <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Array\" target=\"_blank\" rel=\"noopener\">Arrays<\/a>, <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/String\" target=\"_blank\" rel=\"noopener\">Strings<\/a>, <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Set\" target=\"_blank\" rel=\"noopener\">Sets<\/a>, <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Map\" target=\"_blank\" rel=\"noopener\">Maps<\/a>.<\/p>\n<h6>Basic Syntax<\/h6>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/basic syntax\nfor (variable of iterable) {\n  statement;\n}<\/code><\/pre>\n<p>The <code>for..of<\/code> syntax takes following two expressions:<\/p>\n<ul>\n<li><strong>variable<\/strong>: On each iteration a value of a different property is assigned to <em>variable<\/em>.<\/li>\n<li><strong>iterable<\/strong>: Object whose <em>iterable<\/em> properties are iterated.<\/li>\n<\/ul>\n<h6>Iterating over an Array<\/h6>\n<p>In the following example (adopted from the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/for...of#Iterating_over_an_Array\" target=\"_blank\" rel=\"noopener\">MDN Documentation<\/a>) the <code>for..of<\/code> statement is used to iterate over an array because arrays are iterable.<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/initializing myArray\nlet myArray = [20, 25, 30];\n\/\/Iterating over for..of\nfor (let x of myArray) { \/\/using let var\n  x += 1; \/\/ increase value of x by 1\n  console.log(x);\n}\n\/\/OUTPUT\n21\n26\n31<\/code><\/pre>\n<p>The <code>let<\/code> variable (line 4) used in the above example can be replaced with <code>const<\/code> variable (as shown below, line 15), if the variable is NOT re-assign within the block.<\/p>\n<pre class=\"line-numbers\" data-start=\"12\"><code class=\"language-javascript\">\/\/Initializing myArray\nlet myArray = [20, 25, 30];\n\/\/iterating over with for..of\nfor (const x of myArray) { \/\/using a const var\n  console.log(x);\n}\n\/\/OUTPUT\n20\n25\n30<\/code><\/pre>\n<h6>Iterating Over a String<\/h6>\n<p>The <code>for..of<\/code> statement is more reliable to iterate over a <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/String\" target=\"_blank\" rel=\"noopener\">string<\/a>, than the <code>for..in<\/code> statement used in previous section.<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/initializing myString\nlet myString = &quot;TOYOTA&quot;;\n\/\/iterating over a string with for..of\nfor (const x of myString) {\n  console.log(x);\n}\n\/\/OUTPUT\nT\nO\nY\nO\nT\nA<\/code><\/pre>\n<p>As described in <code>for..in<\/code> section, each character in a <em>string<\/em> has an index, which are enumerable. The <code>for..of<\/code> statement is more reliable method to iterate <em>string<\/em> object.<\/p>\n<h6>Iterating Over Map<\/h6>\n<p>Iterating Maps with <code>for..of<\/code> was discussed previously in a <a href=\"https:\/\/tinjurewp.com\/jsblog\/learning-javascript-maps-sets\/\" target=\"_blank\" rel=\"noopener\">separate post<\/a> and the same example is revisited below.<\/p>\n<p>Iteration of maps elements with <code>for..of<\/code> loop goes for each elements in the insertion order and returns an array of <code>[key, value]<\/code> pair.<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/initialize myCar set and add elements\nlet myCar = new Map([[0, &#039;Toyota&#039;], [1, &#039;Honda&#039;], [2, &#039;Ford&#039;]]);\n\n\/\/ iterate to print keys only\nfor (let key of myCar.keys()) {\n  console.log(key);\n}\n\/\/OUTPUT\n0\n1\n2\n\n\/\/iterate values only\nfor (let value of myCar.values()) {\n  console.log(value);\n}\n\/\/OUTPUT\nToyota\nHonda\nFord\n\n\/\/iterate both keys &amp; value\nfor (let [key, value] of myCar) {\n  console.log(key + &#039; = &#039; + value);\n}\n\/\/OUTPUT\n0 = Toyota\n1 = Honda\n2 = Ford<\/code><\/pre>\n<p>In the example above, <code>for..of<\/code> statement is used to <code>myCar<\/code> array to iterate <em>only key<\/em> values in their order of insertion and print return to the console (lines: 4-11). Similarly, we can iterate <em>only values<\/em> using <code>for..of<\/code> statement and print <em>key\/value<\/em> pairs\u00a0 to the console (lines: 14-20) and to iterate both the keys:values (lines: 23-29).<\/p>\n<h6>Iterating Over Set<\/h6>\n<p>Iterating <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Set\" target=\"_blank\" rel=\"noopener\"><code>Sets<\/code><\/a> object with <code>for..of<\/code> was briefly discussed previously in a <a href=\"https:\/\/tinjurewp.com\/jsblog\/learning-javascript-maps-sets\/\" target=\"_blank\" rel=\"noopener\">separate post<\/a>. The <code>for..of<\/code> statement is more reliable method introduced in ES6 to iterate <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Set\" target=\"_blank\" rel=\"noopener\"><code>Sets<\/code><\/a> object.<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/initialize Set Objects \nlet carSet = new Set([&quot;Toyota&quot;, &quot;corolla&quot;, 2018, 2018]); \n\n\/\/iterate Set elements with for..of\nfor (let item of carSet) console.log(item);\n\/\/OUTPUT\nToyota\ncorolla\n2018<\/code><\/pre>\n<p>In the example above, a <code>carSet<\/code> object is created and assigned with four items (line 2). By using <code>for..of<\/code> statement to <code>Set<\/code> object items (line 2), <code>carSet<\/code> object elements can be printed to the console in their order of insertion (lines 7-9).<\/p>\n<p class=\"tip icon-note\"><strong>Tip<\/strong>: There are additional use case examples of for..of iteration listed in the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/for...of#Examples\" target=\"_blank\" rel=\"noopener\">MDN Documentation<\/a> including <em>iterable<\/em> objects, <em>generators<\/em>, <em>DOM collection<\/em>, <em>arguments.<\/em><\/p>\n<h5>Difference Between <code>for..of<\/code> and <code>for..in<\/code><\/h5>\n<p>The difference between the <code>for..in<\/code> statement and the <code>for..of<\/code> statement discussed above are summarized in the following table(adopted from <a href=\"https:\/\/bitsofco.de\/for-in-vs-for-of\/#acomparison\" target=\"_blank\" rel=\"noopener\">bitsofcode<\/a>).<\/p>\n<table class=\"learnjs\">\n<thead>\n<tr>\n<th>Iteration<\/th>\n<th style=\"text-align: center;\"><strong>for..in Loop<br \/>\n<\/strong><\/th>\n<th style=\"text-align: center;\"><strong>for..of loop<br \/>\n<\/strong><\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Suitable for<\/td>\n<td>Enumerable Properties<\/td>\n<td>Iterable Collections<\/td>\n<\/tr>\n<tr>\n<td>Use with Objects?<\/td>\n<td>Yes<\/td>\n<td>No<\/td>\n<\/tr>\n<tr>\n<td>Use with Arrays?<\/td>\n<td>Yes, but not advised<\/td>\n<td>Yes<\/td>\n<\/tr>\n<tr>\n<td>Use with Strings?<\/td>\n<td>Yes, but not advised<\/td>\n<td>Yes<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>The <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/for...of\/#Difference_between_for...of_and_for...in\" target=\"_blank\" rel=\"noopener\">MDN documentation<\/a> describes difference between a <code>for...of<\/code> loop and a <code>for...in<\/code> loop step by step when used with an <a title=\"The JavaScript Array\u00a0object is a global object that\u00a0is used in the\u00a0construction\u00a0of\u00a0arrays; which are high-level, list-like objects.\" href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Array\"><code>Array<\/code><\/a>.<\/p>\n<p class=\"tip icon-note\"><strong>Tip<\/strong>: the <code>for-of<\/code> statement is used for iterating over <em>arrays<\/em> and the <code>for-in<\/code> statement is for iterating over the <em>keys<\/em> of objects.<\/p>\n<h5>Wrapping Up<\/h5>\n<p>In this learning-note post use of <code>for<\/code> statement, <code>for..in<\/code> statement and <code>for..of<\/code> statement to iterate enumerable objects were discussed with some use case examples. Some high lights of the difference between the <code>for..in<\/code> and <code>for..of<\/code> statements were discussed. A more detail discussion on <code>enumeration<\/code> is covered in a separate learning-note post &#8211;\u00a0<a href=\"https:\/\/tinjurewp.com\/jsblog\/deep-dive-into-javascript-property-descriptors\/\" target=\"_blank\" rel=\"noopener\">Deep Dive into JavaScript Property Descriptors<\/a><\/p>\n<p>Related Post: <a href=\"https:\/\/tinjurewp.com\/jsblog\/learning-javascript-while-and-do-while-loops\" target=\"_blank\" rel=\"noopener\">Learning JavaScript While and Do..While Loops<\/a><\/p>\n<h5>Useful Resources &amp; Links<\/h5>\n<p>While preparing this post, I have referred the following references extensively. Visit original link for additional information.<\/p>\n<ul>\n<li><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Guide\/Loops_and_iteration\" target=\"_blank\" rel=\"noopener\">Loop &amp; Iteration<\/a> | MDN Documentation<\/li>\n<li><a href=\"https:\/\/zellwk.com\/blog\/js-for-loops\/\" target=\"_blank\" rel=\"noopener\">Understanding for loops<\/a> | <a href=\"https:\/\/zellwk.com\/blog\/\" target=\"_blank\" rel=\"noopener\">Zell Liew<\/a><\/li>\n<li><a href=\"https:\/\/bitsofco.de\/for-in-vs-for-of\/\" target=\"_blank\" rel=\"noopener\">for..in versus for..of Loops<\/a> | <a href=\"https:\/\/bitsofco.de\/\" target=\"_blank\" rel=\"noopener\">bitsofcode<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Note: This post is work-in-progress learning-note and still in active development and updated regularly. In JS programming, like in other programming languages, there would be a need to do certain task repeatedly, for example to run a block of code to perform repetitive tasks. JS loops offer easy way to perform same task repetitively. There [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_crdt_document":"","footnotes":""},"categories":[49],"tags":[],"class_list":["post-1982","post","type-post","status-publish","format-standard","hentry","category-conditionals"],"_links":{"self":[{"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/posts\/1982","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/comments?post=1982"}],"version-history":[{"count":0,"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/posts\/1982\/revisions"}],"wp:attachment":[{"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/media?parent=1982"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/categories?post=1982"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/tags?post=1982"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}