{"id":42755,"date":"2024-02-29T15:49:28","date_gmt":"2024-02-29T10:19:28","guid":{"rendered":"https:\/\/www.guvi.in\/blog\/?p=42755"},"modified":"2026-09-29T12:18:39","modified_gmt":"2026-09-29T06:48:39","slug":"loops-in-javascript-with-examples","status":"publish","type":"post","link":"https:\/\/www.guvi.in\/blog\/loops-in-javascript-with-examples\/","title":{"rendered":"Loops in JavaScript (2026): A Beginner&#8217;s Guide to Writing Cleaner Code"},"content":{"rendered":"\n<p>Ever needed to print or process the same kind of value seven, seventeen, or seven thousand times, and dreaded typing it out by hand? That&#8217;s exactly the problem loops in JavaScript exist to solve.<\/p>\n\n\n\n<p><strong>Loops in JavaScript are structures that let you run the same block of code again and again, without having to type it out manually every single time.<\/strong> Instead of writing seven console.log() statements to print seven numbers, a single loop handles the repetition for you in just a few lines.<\/p>\n\n\n\n<p>Whether you&#8217;re processing arrays, checking conditions, or just automating a repetitive task, picking the right loop makes your code cleaner and easier to follow. This guide breaks down every loop type in JavaScript, when to use each one, and how they actually work under the hood.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>TL;DR Summary<\/strong><\/h2>\n\n\n\n<ul>\n<li><strong>What it is:<\/strong> loops in JavaScript are structures that let you repeat a block of code without writing it out again and again, saving time and keeping your code clean<\/li>\n\n\n\n<li><strong>Most commonly used:<\/strong> the for loop is the most popular of all the loops in JavaScript, since it packs initialization, condition, and increment into one line<\/li>\n\n\n\n<li><strong>Guaranteed to run once:<\/strong> do&#8230;while checks its condition after running, unlike most other loops in JavaScript that check first<\/li>\n\n\n\n<li><strong>For objects vs arrays:<\/strong> for&#8230;in loops through object properties, for&#8230;of loops through array or iterable values<\/li>\n\n\n\n<li><strong>Extra control:<\/strong> break exits a loop early, continue skips just the current iteration, both work across almost every one of these loops in JavaScript<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Introduction to Loops in JavaScript<\/strong><\/h2>\n\n\n\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" width=\"1200\" height=\"503\" src=\"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/09\/ChatGPT-Image-Sep-29-2026-12_18_07-PM-1200x503.webp\" alt=\"Introduction to Loops in JavaScript\" class=\"wp-image-141332\" srcset=\"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/09\/ChatGPT-Image-Sep-29-2026-12_18_07-PM-1200x503.webp 1200w, https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/09\/ChatGPT-Image-Sep-29-2026-12_18_07-PM-300x126.webp 300w, https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/09\/ChatGPT-Image-Sep-29-2026-12_18_07-PM-768x322.webp 768w, https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/09\/ChatGPT-Image-Sep-29-2026-12_18_07-PM-1536x644.webp 1536w, https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/09\/ChatGPT-Image-Sep-29-2026-12_18_07-PM-150x63.webp 150w, https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/09\/ChatGPT-Image-Sep-29-2026-12_18_07-PM.webp 1938w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" title=\"\"><\/figure>\n\n\n\n<p>Loops in JavaScript are control structures that allow us to repeatedly execute a block of code until a certain condition is met.<\/p>\n\n\n\n<p>They are used when we want to perform an operation multiple times without having to write the same code over and over again. In <a href=\"https:\/\/www.guvi.in\/hub\/javascript\/?utm_source=blog&amp;utm_medium=hyperlink&amp;utm_campaign=loops-in-javascript-with-examples\">JavaScript<\/a>, there are several types of loops, each with its own syntax and use cases.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1) The for Loop<\/h3>\n\n\n\n<p>The for loop is one of the most commonly used loops in JavaScript. It allows us to execute a block of code a specified number of times. The syntax of the for loop is as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>for (initialization; condition; increment) {\n  \/\/ code to be executed\n}<\/code><\/pre>\n\n\n\n<ul>\n<li>The initialization step is executed only once before the loop starts. It is where we declare and initialize any variables used in the loop.<\/li>\n\n\n\n<li>The condition is evaluated before each iteration, and if it evaluates to true, the loop continues.<\/li>\n\n\n\n<li>The increment step is executed after each iteration, and is typically used to update the loop control variable.<\/li>\n<\/ul>\n\n\n\n<p>Let&#8217;s see an example to illustrate the usage of the for loop:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>for (let i = 1; i &lt; 8; i++) {\n  console.log(i);\n}<\/code><\/pre>\n\n\n\n<p>In this example, the loop will iterate seven times, printing the values from 1 to 7 to the console.<\/p>\n\n\n\n<p><strong>Must Read:<\/strong> <a href=\"https:\/\/www.guvi.in\/blog\/javascript-frontend-roadmap\/\">Master JavaScript Frontend Roadmap: From Novice to Expert<\/a><\/p>\n\n\n\n<p>Ready to turn your knowledge of loops in JavaScript into a full career in web development?<\/p>\n\n\n\n<p>HCL GUVI&#8217;s <a href=\"https:\/\/www.guvi.in\/zen-class\/full-stack-development-course\/?utm_source=blog&amp;utm_medium=hyperlink&amp;utm_campaign=loops-in-javascript-with-examples\">Software and AI Engineer Programme<\/a> takes you from core JavaScript fundamentals to full-stack, backend, and AI-powered development, with hands-on projects, mentorship, mock interviews, and IITM-Pravartak certification.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2) The do&#8230;while Loop<\/h3>\n\n\n\n<p>The do&#8230;while loop is similar to the while loop, but with one key difference: the condition is evaluated after the code block has been executed.<\/p>\n\n\n\n<p>This means that the code block will always execute at least once, regardless of the condition. The syntax of the do&#8230;while loop is as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>do {\n  \/\/ code to be executed\n} while (condition);<\/code><\/pre>\n\n\n\n<p>Let&#8217;s look at an example to understand how the do&#8230;while loop works:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>let i = 0;\ndo {\n  console.log(i);\n  i++;\n} while (i &lt; 10);<\/code><\/pre>\n\n\n\n<p>In this example, the code block executes once, printing the value of i to the console. Then the condition i &lt; 10 is checked.<\/p>\n\n\n\n<p>If it evaluates to true, the loop continues, and the code block runs again. This repeats until the condition becomes false, printing 0 through 9. It is one of the most versatile loops in JavaScript.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">3) The while Loop<\/h3>\n\n\n\n<p>Among loops in JavaScript, the while loop is used to execute a block of code as long as a specified condition is true. It is similar to the do&#8230;while loop, but the condition is evaluated before the code block is executed.<\/p>\n\n\n\n<p>The syntax of the while loop is as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>while (condition) {\n  \/\/ code to be executed\n}<\/code><\/pre>\n\n\n\n<p>Let&#8217;s see an example to understand how the while loop works:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>let i = 0;\nwhile (i &lt; 17) {\n  console.log(i);\n  i++;\n}<\/code><\/pre>\n\n\n\n<p>In this example, the code block executes as long as the condition i &lt; 17 is true, printing the values 0 through 16, 17 numbers in total. It is one of the most used loops in JavaScript.<\/p>\n\n\n\n<p><strong>Also Read:<\/strong> <a href=\"https:\/\/www.guvi.in\/blog\/javascript-tools-every-developer-should-know\/\">JavaScript Tools Every Developer Should Know<\/a><\/p>\n\n\n\n<p>Before we move to the next section, make sure that you are strong in the full-stack development basics. If not, consider enrolling for a professionally certified online <a href=\"https:\/\/www.guvi.in\/zen-class\/full-stack-development-course\/?utm_source=blog&amp;utm_medium=hyperlink&amp;utm_campaign=loops-in-javascript-with-examples\">full-stack web development course<\/a> by a recognized institution that can also offer you an industry-grade certificate that boosts your resume.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">4) The Labeled Statement<\/h3>\n\n\n\n<p>Among loops in JavaScript, labels let you identify a loop or a block of code. Labels are often used with the break and continue statements to control the flow of the program. The syntax of a labeled statement is as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>label: statement<\/code><\/pre>\n\n\n\n<p>Let&#8217;s look at an example of using labels with the for loop and the break statement:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>outerLoop: for (let i = 0; i &lt; 9; i++) {\n  innerLoop: for (let j = 0; j &lt; 9; j++) {\n    if (i === 1 &amp;&amp; j === 1) {\n      break outerLoop;\n    }\n    console.log(`i = ${i}, j = ${j}`);\n  }\n}<\/code><\/pre>\n\n\n\n<p>In this example, we have an outer loop labeled as outerLoop and an inner loop labeled as innerLoop.<\/p>\n\n\n\n<p>When the condition i === 1 &amp;&amp; j === 1 is met, the break statement is executed, causing the program to break out of the outer loop entirely, not just the inner one. This allows us to selectively break out of multiple nested loops.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">5) The break Statement<\/h3>\n\n\n\n<p>The break statement is used to exit a loop or switch statement prematurely. When the break statement is encountered, the program flow immediately moves to the next statement outside of the loop or switch.<\/p>\n\n\n\n<p>This is one of the most useful control tools among loops in JavaScript when we want to terminate a loop early based on a certain condition. Let&#8217;s see an example to understand how the break statement works:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>for (let i = 0; i &lt; 7; i++) {\n  if (i === 5) {\n    break;\n  }\n  console.log(i);\n}<\/code><\/pre>\n\n\n\n<p>In this example, the loop prints the values 0 through 4, five values in total. When i becomes 5, the break statement is executed, and the loop is terminated before it ever prints 5.<\/p>\n\n\n\n<p><strong>Develop your first project with us:<\/strong> <a href=\"https:\/\/www.guvi.in\/blog\/html-and-css-project-ideas\/\">10 Best HTML and CSS Project Ideas for Beginners<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">6) The continue Statement<\/h3>\n\n\n\n<p>The continue statement is used to skip the current iteration of a loop and move on to the next iteration. Unlike the break statement, which terminates the loop, the continue statement only affects the current iteration.<\/p>\n\n\n\n<p>This is another useful control tool among loops in JavaScript when we want to skip certain iterations based on a condition. Let&#8217;s look at an example to understand how the continue statement works:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>for (let i = 0; i &lt; 10; i++) {\n  if (i === 9) {\n    continue;\n  }\n  console.log(i);\n}<\/code><\/pre>\n\n\n\n<p>In this example, the loop still runs its full 10 iterations (i = 0 through 9), but when i equals 9, the continue statement skips the console.log for that one iteration. As a result, the values 0 through 8 are printed, nine values total, and 9 never appears in the output.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">7) The for&#8230;in Loop<\/h3>\n\n\n\n<p>Among loops in JavaScript, the for&#8230;in statement is used to iterate over the properties of an object. It allows us to access each property of an object and perform a specific action. The syntax of the for&#8230;in loop is as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>for (variable in object) {\n  \/\/ code to be executed\n}<\/code><\/pre>\n\n\n\n<p>Let&#8217;s see an example to understand how the for&#8230;in loop works:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const person = {\n  name: \"HCLGUVI\",\n  age: 10,\n  city: \"Chennai, Tamil Nadu\"\n};\n\nfor (let key in person) {\n  console.log(`${key}: ${person&#91;key]}`);\n}<\/code><\/pre>\n\n\n\n<p>In this example, the loop iterates over each property of the person object and prints the key-value pairs to the console. The output will be:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>name: HCLGUVI\nage: 10\ncity: Chennai, Tamil Nadu<\/code><\/pre>\n\n\n\n<p><strong>Must Read:<\/strong> <a href=\"https:\/\/www.guvi.in\/blog\/differences-between-and-operators-in-javascript\/\">4 Key Differences Between == and === Operators in JavaScript<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">8) The for&#8230;of Loop<\/h3>\n\n\n\n<p>Among loops in JavaScript, the for&#8230;of statement is used to iterate over iterable objects, such as arrays, strings, and other iterable built-in objects. It provides a simpler and more concise syntax compared to the for loop or the for&#8230;in loop.<\/p>\n\n\n\n<p>The syntax of the for&#8230;of loop is as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>for (variable of iterable) {\n  \/\/ code to be executed\n}<\/code><\/pre>\n\n\n\n<p>Let&#8217;s look at an example to understand how the for&#8230;of loop works:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const languages = &#91;\"javascript\", \"python\", \"html\"];\n\nfor (let lang of languages) {\n  console.log(lang);\n}<\/code><\/pre>\n\n\n\n<p>In this example, the loop iterates over each element in the languages array and prints the value to the console. The output will be:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>javascript\npython\nhtml<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Loops in JavaScript: Quick Comparison Table<\/h2>\n\n\n\n<p>The table below covers all the loops in JavaScript discussed in this guide, comparing how each one works and when to use it:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Loop Type<\/th><th>Best Used For<\/th><th>Executes At Least Once<\/th><th>Key Characteristic<\/th><\/tr><\/thead><tbody><tr><td>for<\/td><td>Running code a fixed, known number of times<\/td><td>No<\/td><td>Combines initialization, condition, and increment in one line<\/td><\/tr><tr><td>while<\/td><td>Repeating code while a condition stays true, when iteration count is unknown<\/td><td>No<\/td><td>Checks the condition before running the code block<\/td><\/tr><tr><td>do&#8230;while<\/td><td>Cases where the code must run at least once before checking the condition<\/td><td>Yes<\/td><td>Checks the condition after running the code block<\/td><\/tr><tr><td>for&#8230;in<\/td><td>Iterating over the properties (keys) of an object<\/td><td>No<\/td><td>Not ideal for arrays since it iterates over keys, not values<\/td><\/tr><tr><td>for&#8230;of<\/td><td>Iterating over values in arrays, strings, and other iterables<\/td><td>No<\/td><td>Cleaner syntax than for&#8230;in when values (not keys) are needed<\/td><\/tr><tr><td>Labeled Statement<\/td><td>Controlling flow in nested loops<\/td><td>No<\/td><td>Used alongside break\/continue to target a specific outer loop<\/td><\/tr><tr><td>break<\/td><td>Exiting a loop early once a condition is met<\/td><td>N\/A (not a loop itself)<\/td><td>Terminates the loop completely<\/td><\/tr><tr><td>continue<\/td><td>Skipping the current iteration without ending the loop<\/td><td>N\/A (not a loop itself)<\/td><td>Moves to the next iteration, skipping remaining code in that cycle<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Loops vs Array Methods: forEach, map, and filter<\/h2>\n\n\n\n<p>Modern JavaScript gives you array methods as an alternative to traditional loops in JavaScript, and it&#8217;s worth knowing when each one actually makes sense.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Approach<\/th><th>Can Use break\/continue?<\/th><th>Returns a New Array?<\/th><th>Best For<\/th><\/tr><\/thead><tbody><tr><td>for \/ while \/ do&#8230;while<\/td><td>Yes<\/td><td>No<\/td><td>Full control, early exit, complex conditions<\/td><\/tr><tr><td>forEach()<\/td><td>No<\/td><td>No<\/td><td>Simple iteration with no need to exit early<\/td><\/tr><tr><td>map()<\/td><td>No<\/td><td>Yes<\/td><td>Transforming every element into a new array<\/td><\/tr><tr><td>filter()<\/td><td>No<\/td><td>Yes<\/td><td>Selecting a subset of elements that match a condition<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<pre class=\"wp-block-code\"><code>const numbers = &#91;1, 2, 3, 4, 5];\n\n\/\/ Traditional loop\nfor (let i = 0; i &lt; numbers.length; i++) {\n  console.log(numbers&#91;i] * 2);\n}\n\n\/\/ Array method equivalent\nnumbers.forEach(num =&gt; console.log(num * 2));\n\n\/\/ map() when you need the transformed values back\nconst doubled = numbers.map(num =&gt; num * 2);\nconsole.log(doubled); \/\/ &#91;2, 4, 6, 8, 10]<\/code><\/pre>\n\n\n\n<p><strong>When to reach for a traditional loop instead:<\/strong> if you need to break out early, skip iterations with continue, or loop over something that isn&#8217;t an array (like object properties), stick with for, while, or for&#8230;in.<\/p>\n\n\n\n<p>Array methods like forEach, map, and filter don&#8217;t support break or continue at all.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Best Practices for Using Loops<\/h2>\n\n\n\n<p>When using loops in JavaScript, it&#8217;s important to follow best practices to ensure clean and efficient code. Here are some tips for using loops effectively:<\/p>\n\n\n\n<ol>\n<li><strong>Use meaningful variable names:<\/strong> Choose variable names that accurately describe the purpose of the loop control variable. This makes the code more readable and understandable.<\/li>\n\n\n\n<li><strong>Initialize variables outside the loop:<\/strong> If possible, initialize loop control variables outside the loop to avoid unnecessary reinitialization.<\/li>\n\n\n\n<li><strong>Use the most appropriate loop for the task:<\/strong> Choose the loop that best fits your code&#8217;s requirements. Use a for loop when you know the number of iterations in advance, and a while loop when the number of iterations is unknown.<\/li>\n\n\n\n<li><strong>Avoid infinite loops:<\/strong> Make sure your loops have a proper exit condition to prevent them from running indefinitely. <a href=\"https:\/\/en.wikipedia.org\/wiki\/Infinite_loop\" target=\"_blank\" rel=\"noopener\">Infinite loops<\/a> can cause your program to crash or become unresponsive.<\/li>\n\n\n\n<li><strong>Minimize code inside loops:<\/strong> Try to keep the code inside loops as concise as possible. Move any complex calculations or resource-intensive operations outside the loop if they don&#8217;t need to be repeated.<\/li>\n\n\n\n<li><strong>Use break and continue judiciously:<\/strong> While break and continue statements can be useful, excessive use can make the code harder to understand and maintain. Use them sparingly and only when necessary.<\/li>\n<\/ol>\n\n\n\n<p><strong>Also Read:<\/strong> <a href=\"https:\/\/www.guvi.in\/blog\/best-javascript-project-ideas\/\">30 Best JavaScript Project Ideas For You [3 Bonus Portfolio Projects]<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common Mistakes to Avoid<\/h2>\n\n\n\n<p>When working with loops in JavaScript, it&#8217;s easy to make mistakes that can lead to bugs or inefficient code. Here are some common mistakes to avoid:<\/p>\n\n\n\n<ol>\n<li><strong>Forgetting to update the loop control variable:<\/strong> Make sure to update the loop control variable inside the loop to avoid infinite loops or incorrect results.<\/li>\n\n\n\n<li><strong>Using the wrong loop type:<\/strong> Choose the appropriate loop type for the task at hand. Using the wrong loop type can lead to unnecessary complexity or inefficiency.<\/li>\n\n\n\n<li><strong>Modifying the iterable object inside a for&#8230;of loop:<\/strong> If you modify the iterable object inside a for&#8230;of loop, it can cause unexpected behavior or errors. Consider creating a copy of the iterable object if you need to modify it.<\/li>\n\n\n\n<li><strong>Not using curly braces for single-line blocks:<\/strong> While it&#8217;s possible to omit curly braces for single-line blocks in loops, it can lead to ambiguity and make the code harder to read. Always use curly braces, even for single-line blocks.<\/li>\n\n\n\n<li><strong>Not initializing loop control variables:<\/strong> Always initialize loop control variables before using them in a loop. Failure to do so can result in undefined behavior or errors.<\/li>\n<\/ol>\n\n\n\n<p><strong>Must Read:<\/strong> <a href=\"https:\/\/www.guvi.in\/blog\/best-reasons-to-learn-javascript\/\">7 Best Reasons to Learn JavaScript | 1 Bonus Point<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Best JavaScript Courses in India 2026: Learn Loops and Core Concepts the Right Way<\/h2>\n\n\n\n<p>If you&#8217;re looking to go beyond just loops in JavaScript and build a career in web development, here are some of the top courses available in India in 2026, ranging from free self-paced options to mentor-led programs with placement support.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Course Name<\/th><th>Offered By<\/th><th>JS Coverage<\/th><th>Link<\/th><\/tr><\/thead><tbody><tr><td>Software and AI Engineer Programme<\/td><td>HCL GUVI<\/td><td>Part of a full MERN stack curriculum (JS is the core scripting language across it)<\/td><td><a href=\"https:\/\/www.guvi.in\/zen-class\/full-stack-development-course\/?utm_source=blog&amp;utm_medium=hyperlink&amp;utm_campaign=loops-in-javascript-with-examples\">Course Page<\/a><\/td><\/tr><tr><td>The Complete JavaScript Course 2026<\/td><td>Jonas Schmedtmann (Udemy)<\/td><td>Dedicated, JS-only course from fundamentals to advanced<\/td><td><a href=\"https:\/\/www.udemy.com\/course\/the-complete-javascript-course\/\" target=\"_blank\" rel=\"noopener\">Course Page<\/a><\/td><\/tr><tr><td>JavaScript Algorithms and Data Structures<\/td><td>freeCodeCamp<\/td><td>Dedicated, JS-only certification<\/td><td><a href=\"https:\/\/www.freecodecamp.org\/learn\/javascript-algorithms-and-data-structures\/\" target=\"_blank\" rel=\"noopener\">Course Page<\/a><\/td><\/tr><tr><td>IBM Full-Stack JavaScript Developer Professional Certificate<\/td><td>IBM (Coursera)<\/td><td>Part of a full-stack curriculum (JS, Node.js, React, Express)<\/td><td><a href=\"https:\/\/www.coursera.org\/professional-certificates\/ibm-full-stack-javascript-developer\" target=\"_blank\" rel=\"noopener\">Course Page<\/a><\/td><\/tr><tr><td>Introduction to JavaScript I<\/td><td>Saylor Academy (via Skill India portal)<\/td><td>Dedicated, JS-only introductory course<\/td><td><a href=\"https:\/\/learn.saylor.org\/course\/info.php?id=502\" target=\"_blank\" rel=\"noopener\">Course Page<\/a><\/td><\/tr><tr><td>Meta Front-End Developer Professional Certificate<\/td><td>Meta (Coursera)<\/td><td>Part of a front-end curriculum (HTML, CSS, JS, React)<\/td><td><a href=\"https:\/\/www.coursera.org\/professional-certificates\/meta-front-end-developer\" target=\"_blank\" rel=\"noopener\">Course Page<\/a><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Loops in JavaScript: Common Interview Questions<\/h2>\n\n\n\n<p>These trip up even experienced developers, since they test how well you actually understand loop mechanics, not just syntax.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Q1. What does this print, and why?<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>for (var i = 0; i &lt; 3; i++) {\n  setTimeout(() =&gt; console.log(\"var:\", i), 0);\n}\nfor (let j = 0; j &lt; 3; j++) {\n  setTimeout(() =&gt; console.log(\"let:\", j), 0);\n}<\/code><\/pre>\n\n\n\n<p><strong>Answer:<\/strong> the var version prints 3, 3, 3, while the let version prints 0, 1, 2. This is because var is function-scoped, so all three callbacks share the same i, which has finished looping (reaching 3) by the time they run. let is block-scoped, so each iteration gets its own separate j.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Q2. How many times does this loop run?<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>let count = 0;\nfor (let i = 10; i &gt; 0; i -= 2) {\n  count++;\n}<\/code><\/pre>\n\n\n\n<p><strong>Answer:<\/strong> 5 times. Starting at 10 and decreasing by 2 each time, i takes the values 10, 8, 6, 4, 2, all greater than 0, and then stops once i reaches 0.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Q3. What does continue with a label actually skip?<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>let result = &#91;];\nouter: for (let i = 0; i &lt; 3; i++) {\n  for (let j = 0; j &lt; 3; j++) {\n    if (j === 1) continue outer;\n    result.push(&#91;i, j]);\n  }\n}<\/code><\/pre>\n\n\n\n<p><strong>Answer:<\/strong> [[0,0], [1,0], [2,0]]. A labeled continue jumps straight to the next iteration of the labeled (outer) loop, not just the inner one, so as soon as j hits 1, the inner loop is abandoned entirely and i moves forward.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>Loops in JavaScript are a fundamental tool in the language, allowing us to execute a block of code repeatedly.<\/p>\n\n\n\n<p>In this comprehensive guide, we have explored the different types of loops in JavaScript, including the for, do&#8230;while, while, for&#8230;in, and for&#8230;of loops. We have also discussed best practices for using loops and common mistakes to avoid.<\/p>\n\n\n\n<p>By mastering all the loops in JavaScript and the art of looping, you can write more efficient and powerful JavaScript code.<\/p>\n\n\n\n<p><strong>Must Explore:<\/strong> <a href=\"https:\/\/www.guvi.in\/blog\/guide-for-variables-and-data-types-in-javascript\/\">Variables and Data Types in JavaScript: A Complete Guide<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>FAQs<\/strong><\/h2>\n\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1785916431889\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">1. What are the main four types of loops?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>The four main loops in JavaScript are <code>for<\/code>, <code>while<\/code>, <code>do...while<\/code>, and <code>for...in<\/code>\/<code>for...of<\/code>. <code>for<\/code> runs a block a set number of times, <code>while<\/code> keeps running as long as a condition is true, <code>do...while<\/code> runs at least once before checking the condition, and <code>for...in<\/code>\/<code>for...of<\/code> are used to loop through object properties or array\/iterable values.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1785916517894\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">2. What are loops and arrays?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Loops are used to repeat a block of code multiple times without writing it out manually. Arrays are data structures that store ordered collections of values. The two are often used together \u2014 loops like <code>for<\/code> or <code>for...of<\/code> let you go through each element in an array and work with its values one by one.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1785916519208\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">3. What is the most commonly used loop in JavaScript?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>The <code>for<\/code> loop is the most widely used, since it combines initialization, condition, and increment in a single line, giving clear control when the number of iterations is known in advance.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1785916520597\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">4. Which loop is faster in JavaScript?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>The traditional <code>for<\/code> loop is generally the fastest, since <code>for...in<\/code> also checks inherited properties and <code>for...of<\/code> relies on iterators, both of which add slight overhead. For small to medium datasets though, the speed difference is barely noticeable.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1785916521755\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">5. Why use loops in JavaScript?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Loops let you repeat an action \u2014 like processing array elements or checking a condition \u2014 without duplicating code. This keeps programs shorter, cleaner, and easier to update later.<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>Ever needed to print or process the same kind of value seven, seventeen, or seven thousand times, and dreaded typing it out by hand? That&#8217;s exactly the problem loops in JavaScript exist to solve. Loops in JavaScript are structures that let you run the same block of code again and again, without having to type [&hellip;]<\/p>\n","protected":false},"author":65,"featured_media":136353,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[429,294],"tags":[],"views":"12429","authorinfo":{"name":"Jebasta","url":"https:\/\/www.guvi.in\/blog\/author\/jebasta\/"},"thumbnailURL":"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2024\/02\/Loops-in-JavaScript-300x116.webp","_links":{"self":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/42755"}],"collection":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/users\/65"}],"replies":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/comments?post=42755"}],"version-history":[{"count":53,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/42755\/revisions"}],"predecessor-version":[{"id":141334,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/42755\/revisions\/141334"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/media\/136353"}],"wp:attachment":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/media?parent=42755"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/categories?post=42755"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/tags?post=42755"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}