{"id":1910,"date":"2018-07-20T21:33:22","date_gmt":"2018-07-20T21:33:22","guid":{"rendered":"https:\/\/tinjurewp.com\/jsblog\/?p=1910"},"modified":"2018-07-20T21:33:22","modified_gmt":"2018-07-20T21:33:22","slug":"learning-javascript-while-and-do-while-loops","status":"publish","type":"post","link":"https:\/\/learncode.tinjurewp.com\/learning-javascript-while-and-do-while-loops\/","title":{"rendered":"Learning JavaScript While and Do..While Loops"},"content":{"rendered":"<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 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. In this learning-note post, we will discuss <code>while<\/code> and <code>do..while<\/code> statements, which are similar to conditional statements. While conditional statements are run only once, a loop executes multiple times until the conditions evaluates <code>true<\/code>.<\/p>\n<p>Other common type of JS loops are <code>for<\/code>, <code>for..in<\/code>, <code>for..of<\/code> statements which will be discussed in separate learning post &#8211; <a href=\"https:\/\/tinjurewp.com\/jsblog\/understanding-javascript-for-loops\" target=\"_blank\" rel=\"noopener\">Understanding JavaScript For Loops<\/a>.<\/p>\n<h3>While statement<\/h3>\n<p>The <code>while<\/code> statements are conditional statements, similar to the <code>if<\/code> statements. Before starting an iteration, conditions are evaluated and if exit-condition it returns <code>true<\/code> the code body (statements) is executed until it is returned <code>false<\/code>.<\/p>\n<h6>Basic Syntax<\/h6>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/basic syntax\nwhile (condition) { \/\/ exit condition\n    statement; \/\/code block to run\n    statement; \/\/ code block to run\n    ....\n}<\/code><\/pre>\n<p>A basic syntax of a <code>while<\/code> statement is shown above. If the exit condition (line 2) becomes <code>false<\/code> then code execution stops and passed to next to <code>while<\/code> statements.<\/p>\n<ul>\n<li><strong>condition<\/strong> : the condition test occurs before code block is executed. If condition is <code>true<\/code>, the code block is executed and condition is tested again. As long as the condition is <code>true<\/code> the body code is executed until the condition returns <code>false<\/code>.<\/li>\n<li><strong>statement<\/strong> : the code block to be executed as long as the exit condition evaluates <code>true<\/code>.<\/li>\n<\/ul>\n<h6>Example 1<\/h6>\n<p>In the following example from the MDN, the <code>while<\/code> statement executes as long as <code>a<\/code> is less than <code>4<\/code>.<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/initialize var to zero\nlet a = 0;\nlet b = 0;\n\/\/ loop through while\nwhile (a &lt; 4) {\n  a++;\n  b += a;\n}\n\/\/OUTPUT\n10<\/code><\/pre>\n<p>In the example above, the <code>a<\/code> &amp; <code>b<\/code> variables are initialized to <code>zero<\/code>. With each iteration, the loop increases <code>a<\/code> (line 6) and adds that value to <code>b<\/code> (line 7). Lets examine these iterations part step by step:<\/p>\n<ul>\n<li>Step 1: The iterator, <code>a<\/code> &amp; <code>b<\/code> start at <code>zero<\/code> (lines: 2-3). Execution condition is evaluated which to run &amp; re-run the loop until <code>a<\/code> is smaller than <code>5<\/code> (line 4).<\/li>\n<li>After the first pass: <code>a<\/code> = 1 and <code>b<\/code> = 1<\/li>\n<li>After the second pass: <code>a<\/code> = 2 and <code>b<\/code> = 3<\/li>\n<li>After third pass: <code>a<\/code> = 3 and <code>b<\/code> = 6<\/li>\n<li>After the fourth pass: <code>a<\/code> = 4 and <code>b<\/code> = 10<\/li>\n<\/ul>\n<p>After the fourth pass, the condition <code>a &lt; 4<\/code> is no longer <code>true<\/code> and the loop terminates.<\/p>\n<h6>Example 2<\/h6>\n<p>In the example below, the condition (line 1) never becomes <code>false<\/code>. Such iterations are called <strong>infinite loops<\/strong>.\u00a0 A loop condition MUST become <code>false<\/code> otherwise the loop will never terminate.<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/ Initiate an infinite loop\nwhile (true) { \/\/exit condition\n    \/\/ execute code forever\n}<\/code><\/pre>\n<p class=\"warning icon-warning\"><strong>Avoid Infinite Loops<\/strong>: When the condition of the <code>while<\/code> statement is set to <code>true<\/code> the code will run forever. It would crash the browser or computer.<\/p>\n<h3>Do..While Statement<\/h3>\n<p>The <code>do..while<\/code> loop statement is variant of the <code>while<\/code> loop statement. In case of the <code>while<\/code> loop, condition is evaluated first before execution of code block, where as in <code>do..while<\/code> loop the code block is executed before it evaluates whether condition is <code>true<\/code>. If the condition is <code>true<\/code> then it re-executes as long it the condition is <code>true<\/code> and stops when it the condition is <code>false<\/code>.<\/p>\n<h6>Basic Syntax<\/h6>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/basic syntax\ndo {\n    statement; \/\/code block to run\n    statement; \/\/code block to run\n    ...\n} while (condition); \/\/exit condition<\/code><\/pre>\n<p>The basic <code>do..while<\/code> syntax is shown above.<\/p>\n<ul>\n<li><strong>statement<\/strong> : executed once before condition is evaluated and\u00a0 the code block is re-executed until the condition evaluates <code>false<\/code>.<\/li>\n<li><strong>condition<\/strong> : The exit condition is evaluated after each iteration and re-executed as long as the condition evaluates t<code>rue<\/code>. If the exit condition evaluates <code>false<\/code>, the loop iteration stops and passes to next block of code.<\/li>\n<\/ul>\n<h6>Example 1<\/h6>\n<p>In the following example from the MDN, the <code>do<\/code> statement executes at least once and thereafter re-iterates until <code>a<\/code> is less than <code>5<\/code>.<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/initialize var a to zero\nlet a = 0;\n\/\/ loop through do..white\ndo {\n  a += 1; \/\/increment by 1\n  console.log(a);\n} while (a &lt; 5); \/\/ exit condition\n\/\/OUTPUT\n1\n2\n3\n4\n5<\/code><\/pre>\n<p>In the example above, var <code>a<\/code> is initialized to zero (line 2). The do statement block executes (line 5) as a result value of <code>a<\/code> increases to 1 (line 5) and printed in console (line 9). After this first iteration, it check the condition <code>a &lt; 5<\/code> (line 7) and since it is less than 5 it returns <code>true<\/code> and the loop body (line 5) re-executes which increases the value <code>a<\/code> to 2 and so on. After the fifth pass, when value of <code>a<\/code> is no longer smaller than 5, the condition fails and the loop terminates.<\/p>\n<h6>Example 2<\/h6>\n<p>In the following example, the <code>do..while<\/code> loop statement is applied to list array items using <code>&lt;a href=&quot;https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Array\/length&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;array.length&lt;\/a&gt;<\/code> property discussed in <a href=\"https:\/\/tinjurewp.com\/jsblog\/understanding-javascript-arrays\/\">array learning-note post<\/a>.<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/initialize cars array\nlet cars = [&quot;Toyota&quot;, &quot;Ford&quot;, &quot;GMC&quot;, &quot;Honda&quot;];\nlet x = 0;\n\/\/ loop through do..while\ndo {\n  console.log(cars[x]);        \n  x++;\n}\nwhile (x &lt; cars.length)\n\/\/OUTPUT\nToyota\nFord\nGMC\nHonda<\/code><\/pre>\n<p>In the example above, <code>cars<\/code> array with four car items is loop through with <code>do...while<\/code> statement and <code>array.length<\/code> property (lines 4-8) to printout array list (lines 10-13).<\/p>\n<p class=\"warning icon-warning\"><strong>Important<\/strong>.\u00a0With <code>for<\/code> \u2014 as with all loops \u2014 you must make sure that the <em>initializer<\/em> is iterated so that it eventually reaches the exit condition. If not, the loop will go on forever, and either the browser will force it to stop, or it will crash. This is called an <strong>infinite loop<\/strong> [Source: <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Learn\/JavaScript\/Building_blocks\/Looping_code#The_standard_for_loop\" target=\"_blank\" rel=\"noopener\">MDN<\/a>]<\/p>\n<h3>Break\/Continue Statements<\/h3>\n<p>The <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/break\" target=\"_blank\" rel=\"noopener\">break<\/a> and <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/continue\" target=\"_blank\" rel=\"noopener\">continue<\/a> statements are used to either break \u201c<em>out of<\/em>\u201d the loop or \u201c<em>jump over<\/em>\u201d one iteration of the loop. The <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/break\" target=\"_blank\" rel=\"noopener\">break<\/a> statement is very useful to terminate an <strong>infinite loops<\/strong>.<\/p>\n<p class=\"note icon-note\"><strong>Note<\/strong>: Use of <code>break<\/code> and <code>continue<\/code> keyword in the <code>&lt;a href=&quot;https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/for&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;for&lt;\/a&gt;<\/code> statements will be discussed in a separate post.<\/p>\n<h5>The Break Statement<\/h5>\n<p>To quote from the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/break\" target=\"_blank\" rel=\"noopener\">MDN documentation<\/a>, \u201c<em>the <strong>break statement<\/strong> terminates the current loop, <a title=\"The switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case, as well as statements in\u00a0cases that follow the matching case.\" href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/switch\"><code>switch<\/code><\/a>, or <a title=\"The labeled statement can be used with break or continue statements. It is prefixing a statement with an identifier which you can refer to.\" href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/label\"><code>label<\/code><\/a> statement and transfers program control to the statement following the terminated statement<\/em>\u201c.<\/p>\n<p>The <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/break\" target=\"_blank\" rel=\"noopener\"><code>break<\/code><\/a> statement uses optional <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/label\" target=\"_blank\" rel=\"noopener\"><code>label<\/code><\/a> statement (discussed below) which allows to terminate a <code>labeled<\/code> statement from the loop. The <code>break<\/code> statement should be nested within the reference <code>label<\/code> statement.<\/p>\n<h6>Example<\/h6>\n<p>In the example below, a <code>break<\/code> statement is used to break out of <code>while<\/code> statement in the loop.<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/initialize var to zero\nlet x = 0;\n\n\/\/loop with while\nwhile (x &lt; 6) { \/\/exit condition\n  if (x === 3) {\n    break;  \/\/use of break \n  }\n  x = x + 1; \/\/increment by 1\n  console.log(x);\n}\n\/\/OUTPUT\n1\n2\n3<\/code><\/pre>\n<p>In the example above, a <code>break<\/code> statement (line 7) terminates the <code>while<\/code> loop when the condition value of <code>x<\/code> reaches <code>3<\/code>. When <code>x===3<\/code>, the <code>break<\/code> statement is kicked in and the iteration terminates out of the loop, as shown in the out put (lines: 13-15).<\/p>\n<h5>The Continue Statement<\/h5>\n<p>Quoting from the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/continue\" target=\"_blank\" rel=\"noopener\">MDN Documentation<\/a> \u201c<em>the <strong>continue statement<\/strong> terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration<\/em>.\u201d<\/p>\n<p>In contrast to the <code>break<\/code> statement discussed above, the <code>continue<\/code> statement does not terminate the loop but it jumps back to the <code>while<\/code> condition or expression update in the <code>for<\/code> loop.<\/p>\n<p>Just like in the <code>break<\/code> statement, the <code>continue<\/code> statement can also be combined with the <code>label<\/code> statement, which allows to jump to the next iteration of a <code>labelled<\/code> loop statement.<\/p>\n<h6>Example<\/h6>\n<p>In the example below, a <code>continue<\/code> statement is nested within a <code>while<\/code> loop when a defined condition is returned <code>true<\/code>.<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/basic syntax\ncontinue [label]; \/\/use label parameter if not used in a loop\n\n\/\/initialize variables\nlet a= 0;\nlet b = 0;\n\/\/ while loop\nwhile (a &lt; 5) { \/\/exit condition\n  a++;\n  console.log(b);\n  \/\/ use continue to skip iteration\n  if (a === 3) { \/\/continue condition\n    continue;\n  }\n\/\/reassign b value\n  b += a;\n}\n\/\/OUTPUT - skips 3rd iteration\n0\n1 \n3\n7\n12<\/code><\/pre>\n<p>In the example above from the MDN, the <code>while<\/code> loop with <code>continue<\/code> key word is used. When the value of <code>a<\/code> is 3 it skips the iteration moves to the next iteration thus skipping an output value (6) of third iteration.<\/p>\n<h3>The Label statement<\/h3>\n<p>The <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/label\" target=\"_blank\" rel=\"noopener\"><code>label<\/code> statement<\/a> as referred in the <em>MDN Documentation<\/em> can be used with <a title=\"The break statement terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.\" href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/break\"><code>break<\/code><\/a> or <a title=\"The continue statement terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.\" href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/continue\"><code>continue<\/code><\/a> statements. It is prefixing a statement with an identifier which you can refer to.<\/p>\n<p>A <code>label<\/code> statement can be used to identify a loop and combining with the <code>break<\/code> or <code>continue<\/code> statements a execution of a loop could be interrupted or continued.<\/p>\n<h6>Example<\/h6>\n<p>In the following simple example of a <code>for<\/code> loop, variable <code>a<\/code> is declared and initialized to <code>zero<\/code> (line 2). It first evaluates if <code>a<\/code> is less than <code>4<\/code> and returns <code>true<\/code> it executes statements and <code>a<\/code> is increment by <code>1<\/code> after each iteration. When condition evaluates <code>false<\/code> loop execution terminates.<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/initialize variable\nlet a = 0;\n\/\/looping with for\nfor (a = 0; a &lt;= 4; a++){\n  console.log(a);\n}\n\/\/OUTPUT\n0\n1\n2\n3\n4<\/code><\/pre>\n<p>In the example above a simple for statement loop is used to execute 4 iterations, with the value of a increasing from 0 to 4. After each iteration, it will log the value of <code>a<\/code> on the console.<\/p>\n<p>Now lets use the <code>label<\/code> statement to name the above loop.<\/p>\n<pre class=\"line-numbers\" data-start=\"13\"><code class=\"language-javascript\">\/\/initialize var to zero\nlet a = 0;\n\/\/iterate with for\neven: \/\/label name\nfor (a = 0; a &lt;= 6; a++){\n  if (a % 2 == 1) continue even;\n  console.log(a);\n}\n\/\/OUTPUT\n0\n2\n4\n6<\/code><\/pre>\n<p>In the example above, our previous <code>for<\/code> loop example is modified by adding a <code>label<\/code> named <code>even<\/code> (line 16).\u00a0 In line 18, a conditional statement with <code>a % 2 == 1<\/code> is added with <code>if<\/code> statement and followed by <code>continue<\/code> <code>even<\/code> (label name of the outer loop). What does this internal <code>if<\/code> loop does is that it evaluates value of <code>a<\/code> after each iteration and when <code>a%2<\/code> is <code>1<\/code> (or odd value) then it instructs to skip the iteration with <code>continue<\/code> statement and move to the next iteration. Therefore, all odd values are skipped and only even values of <code>a<\/code> are printed on the console (lines: 22-25).<\/p>\n<p>The <code>label<\/code> statement is especially useful in nested loop because it allows to use <code>break<\/code> or <code>continue<\/code> statements to selectively terminate or continue some parts of loop execution.<\/p>\n<p class=\"note icon-tip\">Note: <code>Labeled<\/code> loops or blocks are very uncommon. Usually function calls can be used instead of loop jumps. Source: MDN.<\/p>\n<h5>Wrapping Up<\/h5>\n<p>In this learning-note post use of <code>while<\/code> loop, <code>do..while<\/code> loop to iterate some defined repetitive tasks were examined. Use of the <code>break\/continue<\/code> statements to either break \u201c<em>out of<\/em>\u201d the loop or \u201c<em>jump over<\/em>\u201d one iteration of the loop were examined. Another common type of loop using <code>for<\/code> statement will be discussed separately in the next learning-note post.<\/p>\n<p>Related Post: <a href=\"https:\/\/tinjurewp.com\/jsblog\/understanding-javascript-for-loops\" target=\"_blank\" rel=\"noopener\">Understanding JavaScript For Loops<\/a><\/p>\n<h6>Useful Resources &amp; Links<\/h6>\n<p>While preparing this post, I have referred the following references extensively. Visit original link for additional information.<\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Guide\/Loops_and_iteration\" target=\"_blank\" rel=\"noopener\">Loops and Iterations<\/a> | <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Guide\" target=\"_blank\" rel=\"noopener\">MDN JavaScript Guide<\/a><\/li>\n<li><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Learn\/JavaScript\/Building_blocks\/Looping_code\" target=\"_blank\" rel=\"noopener\">Looping Codes<\/a> | MDN Documentation<\/li>\n<li><a href=\"https:\/\/medium.freecodecamp.org\/exploring-javascript-for-in-loops-bdfc226d8515\" target=\"_blank\" rel=\"noopener\">Exploring JavaScript Iteration<\/a> | FreeCodeCamp<\/li>\n<li><a href=\"https:\/\/javascript.info\/while-for\" target=\"_blank\" rel=\"noopener\">Loops: while and for<\/a> | The Modern JavaScript Tutorial<\/li>\n<\/ul>\n<\/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 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 are [&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,4],"tags":[],"class_list":["post-1910","post","type-post","status-publish","format-standard","hentry","category-conditionals","category-javascript"],"_links":{"self":[{"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/posts\/1910","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=1910"}],"version-history":[{"count":0,"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/posts\/1910\/revisions"}],"wp:attachment":[{"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/media?parent=1910"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/categories?post=1910"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/tags?post=1910"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}