{"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-01-19T17:57:27","modified_gmt":"2026-01-19T12:27:27","slug":"loops-in-javascript-with-examples","status":"publish","type":"post","link":"https:\/\/www.guvi.in\/blog\/loops-in-javascript-with-examples\/","title":{"rendered":"All About Loops in JavaScript: A Comprehensive Guide"},"content":{"rendered":"\n<p>Loops are an essential part of any programming language, and JavaScript is no exception. They allow us to execute a set of instructions repeatedly, making our code more efficient and reducing redundancy. <\/p>\n\n\n\n<p>In this comprehensive guide, we will explore the different types of loops in JavaScript, their syntax, and how to effectively use them in your code.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to Loops in JavaScript<\/h2>\n\n\n\n<p>Loops 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 operate multiple times without having to write the same code over and over again. In <a href=\"https:\/\/www.guvi.in\/hub\/javascript\/\" target=\"_blank\" data-type=\"link\" data-id=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\" rel=\"noreferrer noopener\">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 <code>for<\/code> Loop<\/h3>\n\n\n\n<p>The <code>for<\/code> 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 <strong>loop<\/strong> is as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>for (initialization; condition; increment) {\n  \/\/ code to be executed\n}<\/strong><\/code><\/pre>\n\n\n\n<ul>\n<li>The <code>initialization<\/code> The 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 <code>condition<\/code> is evaluated before each iteration, and if it evaluates to <code>true<\/code>The loop continues. <\/li>\n\n\n\n<li>The <code>increment<\/code> 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<strong> example to illustrate the usage of the <code>for<\/code> loop:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>for (let i = 1; i &lt; 8; i++) {\n  console.log(i);\n}<\/strong><\/code><\/pre>\n\n\n\n<p>In this example, the loop will iterate five times, printing the values from 1 to 7 to the console.<\/p>\n\n\n\n<p><strong><em>Must Read: <a href=\"https:\/\/www.guvi.in\/blog\/javascript-frontend-roadmap\/\" target=\"_blank\" rel=\"noreferrer noopener\">Master JavaScript Frontend Roadmap: From Novice to Expert<\/a><\/em><\/strong><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2) The <code>do...while<\/code> Loop<\/h3>\n\n\n\n<p>The <code>do...while<\/code> Loop is similar to the <code>while<\/code> 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<strong> syntax of the <code>do...while<\/code> The loop is as follows:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>do {\n  \/\/ code to be executed\n} while (condition);<\/strong><\/code><\/pre>\n\n\n\n<p>Let&#8217;s look at an <strong>example to understand how the <code>do...while<\/code> loop works:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>let i = 0;\ndo {\n  console.log(i);\n  i++;\n} while (i &lt; 10);<\/strong><\/code><\/pre>\n\n\n\n<p>In this example, the code block will execute once, printing the value  <code>i<\/code> to the console. Then, the condition <code>i &lt; <\/code>10 is checked. <\/p>\n\n\n\n<p>If it evaluates to <code>true<\/code>The loop continues, and the code block is executed again. This process repeats until the condition becomes <code>false<\/code>. It is one of the most versatile loops in JavaScript.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">3) The <code>while<\/code> Loop<\/h3>\n\n\n\n<p>The <code>while<\/code> A loop is used to execute a block of code as long as a specified condition is <code>true<\/code>. It is similar to the <code>do...while<\/code> loop, but the condition is evaluated before the code block is executed. <\/p>\n\n\n\n<p>The <strong>syntax of the <code>while<\/code> The loop <\/strong>is as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>while (condition) {\n  \/\/ code to be executed\n}<\/strong><\/code><\/pre>\n\n\n\n<p>Let&#8217;s see an <strong>example to understand how the <code>while<\/code> loop works:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>let i = 0;\nwhile (i &lt; 17) {\n  console.log(i);\n  i++;\n}<\/strong><\/code><\/pre>\n\n\n\n<p>In this example, the code block will execute as long as the condition <code>i &lt; <\/code>17 is <code>true<\/code>. The value of <code>i<\/code> will be printed to the console and then <code>i<\/code> will be incremented by 1.<\/p>\n\n\n\n<p>This process will repeat until the condition becomes <code>false<\/code>. It is one of the most used loops in JavaScript.<\/p>\n\n\n\n<p><strong>Also Read: <a href=\"https:\/\/www.guvi.in\/blog\/javascript-tools-every-developer-should-know\/\" target=\"_blank\" data-type=\"link\" data-id=\"https:\/\/www.guvi.in\/blog\/javascript-tools-every-developer-should-know\/\" rel=\"noreferrer noopener\">JavaScript Tools Every Developer Should Know<\/a><\/strong><\/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\" target=\"_blank\" rel=\"noreferrer noopener\">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 <strong>Labeled <\/strong>Statement<\/h3>\n\n\n\n<p>In JavaScript, you can use labels to identify a loop or a block of code. Labels are often used with the <code>break<\/code> and <code>continue<\/code> statements to control the flow of the program. The <strong>syntax of a labeled statement<\/strong> is as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>label: statement<\/strong><\/code><\/pre>\n\n\n\n<p>Let&#8217;s look at an <strong>example of using labels with the <code>for<\/code> loop and the <code>break<\/code> statement:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>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}<\/strong>\n<\/code><\/pre>\n\n\n\n<p>In this example, we have an outer loop labeled as <code>outerLoop<\/code> and an inner loop labeled as <code>innerLoop<\/code>. When the condition <code>i === 1 &amp;&amp; j === 1<\/code> is met, the <code>break<\/code> The statement is executed, causing the program to break out of the outer loop. This allows us to selectively break out of multiple nested loops.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">5) The <code>break<\/code> Statement<\/h3>\n\n\n\n<p>The <code>break<\/code> The statement is used to exit a loop or switch statement prematurely. When the <code>break<\/code> 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 useful when we want to terminate a loop early based on a certain condition. Let&#8217;s see <strong>an example to understand how the <code>break<\/code> statement works:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>for (let i = 0; i &lt; 7; i++) {\n  if (i === 5) {\n    break;\n  }\n  console.log(i);\n}<\/strong><\/code><\/pre>\n\n\n\n<p>In this example, the loop will iterate four times, printing the values from 0 to 4 to the console. When <code>i<\/code> it becomes 5, the <code>break<\/code> statement is executed, and the loop is terminated.<\/p>\n\n\n\n<p><strong><em>Develop your first project with us: <a href=\"https:\/\/www.guvi.in\/blog\/html-and-css-project-ideas\/\" target=\"_blank\" rel=\"noreferrer noopener\">10 Best HTML and CSS Project Ideas for Beginners<\/a><\/em><\/strong><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">6) The <code>continue<\/code> Statement<\/h3>\n\n\n\n<p>The <code>continue<\/code> The statement is used to skip the current iteration of a loop and move on to the next iteration. Unlike the <code>break<\/code> statement, which terminates the loop, the <code>continue<\/code> statement only affects the current iteration. <\/p>\n\n\n\n<p>This is useful when we want to skip certain iterations based on a condition. Let&#8217;s look at an<strong> example to understand how the <code>continue<\/code> statement works:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>for (let i = 0; i &lt; 10; i++) {\n  if (i === 9) {\n    continue;\n  }\n  console.log(i);\n}<\/strong><\/code><\/pre>\n\n\n\n<p>In this example, the loop will iterate five times, but when <code>i<\/code> is equal to 9, the <code>continue<\/code> The statement is executed, and the code block is skipped for that iteration. As a result, the value 9 is not printed to the console.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">7) The <code>for...in<\/code> Loop<\/h3>\n\n\n\n<p>The <code>for...in<\/code> A 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 The <strong>loop<\/strong> is as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>for (variable in object) {\n  \/\/ code to be executed\n}<\/strong><\/code><\/pre>\n\n\n\n<p>Let&#8217;s see an <strong>example to understand how the <code>for...in<\/code> loop works:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>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}<\/strong><\/code><\/pre>\n\n\n\n<p>In this example, the loop will iterate over each property of the <code>person<\/code> object and print the key-value pairs to the console. The output will be:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>name: HCLGUVI\nage: 10\ncity: Chennai, Tamil Nadu<\/strong><\/code><\/pre>\n\n\n\n<p><strong><em>Must Read: <a href=\"https:\/\/www.guvi.in\/blog\/differences-between-and-operators-in-javascript\/\" target=\"_blank\" rel=\"noreferrer noopener\">4 Key Differences Between == and === Operators in JavaScript<\/a><\/em><\/strong><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">8) The <code>for...of<\/code> Loop<\/h3>\n\n\n\n<p>The <code>for...of<\/code> 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 <code>for<\/code> loop or the <code>for...in<\/code> loop.<\/p>\n\n\n\n<p>The <strong>syntax of the <code>for...of<\/code> The loop<\/strong> is as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>for (variable of iterable) {\n  \/\/ code to be executed\n}<\/strong><\/code><\/pre>\n\n\n\n<p>Let&#8217;s look at an<strong> example to understand how the <code>for...of<\/code> loop works:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>const languages = &#91;\"javascript\", \"python\", \"html\"];\n\nfor (let lang of languages) {\n  console.log(lang);\n}<\/strong><\/code><\/pre>\n\n\n\n<p>In this example, the loop will iterate over each element in the <code>fruits<\/code> array and print the value to the console. The output will be:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>javascript\npython\nhtml<\/strong><\/code><\/pre>\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 the requirements of your code. For example, use a&nbsp;<code>for<\/code>&nbsp;loop when you know the number of iterations in advance, and use a&nbsp;<code>while<\/code>&nbsp;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. Infinite loops 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&nbsp;<code>break<\/code>&nbsp;and&nbsp;<code>continue<\/code>&nbsp;judiciously: <\/strong>While&nbsp;<code>break<\/code>&nbsp;and&nbsp;<code>continue<\/code>&nbsp;Statements can be useful, but 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: <a href=\"https:\/\/www.guvi.in\/blog\/best-javascript-project-ideas\/\" target=\"_blank\" data-type=\"link\" data-id=\"https:\/\/www.guvi.in\/blog\/best-javascript-project-ideas\/\" rel=\"noreferrer noopener\">30 Best JavaScript Project Ideas For You [3 Bonus Portfolio Projects]<\/a><\/strong><\/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&nbsp;<code>for...of<\/code>&nbsp;loop:<\/strong> If you modify the iterable object inside a&nbsp;<code>for...of<\/code>&nbsp;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: <a href=\"https:\/\/www.guvi.in\/blog\/best-reasons-to-learn-javascript\/\" target=\"_blank\" data-type=\"link\" data-id=\"https:\/\/www.guvi.in\/blog\/best-reasons-to-learn-javascript\/\" rel=\"noreferrer noopener\">7 Best Reasons to Learn JavaScript | 1 Bonus Point<\/a><\/strong><\/p>\n\n\n\n<p class=\"has-text-align-center\"><em><strong>If you want to learn more about JavaScript as well as web development and make a successful career out of it, then you must sign up for the Certified <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\" target=\"_blank\" rel=\"noreferrer noopener\">Full Stack Development Course<\/a>, offered by HCL GUVI, which gives you in-depth knowledge of the practical implementation of all frontend as well as <a href=\"https:\/\/www.guvi.in\/blog\/guide-on-backend-development\/\" target=\"_blank\" rel=\"noreferrer noopener\">backend development<\/a> through various real-life FSD projects.<\/strong><\/em><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Concluding Thoughts&#8230;<\/h2>\n\n\n\n<p>Loops are a fundamental tool in JavaScript programming, 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 <code>for<\/code>, <code>do...while<\/code>, <code>while<\/code>, <code>for...in<\/code>, and <code>for...of<\/code> 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: <a href=\"https:\/\/www.guvi.in\/blog\/guide-for-variables-and-data-types-in-javascript\/\" target=\"_blank\" data-type=\"link\" data-id=\"https:\/\/www.guvi.in\/blog\/guide-for-variables-and-data-types-in-javascript\/\" rel=\"noreferrer noopener\">Variables and Data Types in JavaScript: A Complete Guide<\/a><\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">FAQs<\/h2>\n\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1709015465884\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">What are JavaScript loops?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>JavaScript loops are control structures that allow for repetitive execution of code.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1709015494359\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">How many loops are there in JavaScript?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>There are four types of loops in JavaScript: for loop, while loop, do-while loop, and for&#8230;of loop.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1709015496005\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">What is the use of for of loop in JavaScript?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>The for&#8230;of loop in JavaScript is used to iterate over iterable objects such as arrays, strings, maps, sets, etc. Dive into the article above to gain a better understanding of all loops in JavaScript.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1709015497882\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">What is an array in JavaScript?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>An array in JavaScript is a special variable that can hold more than one value at a time.<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>Loops are an essential part of any programming language, and JavaScript is no exception. They allow us to execute a set of instructions repeatedly, making our code more efficient and reducing redundancy. In this comprehensive guide, we will explore the different types of loops in JavaScript, their syntax, and how to effectively use them in [&hellip;]<\/p>\n","protected":false},"author":16,"featured_media":43219,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[429,294],"tags":[],"views":"10709","authorinfo":{"name":"Jaishree Tomar","url":"https:\/\/www.guvi.in\/blog\/author\/jaishree\/"},"thumbnailURL":"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2024\/02\/Feature-Image-All-About-Loops-in-JavaScript-A-Comprehensive-Guide-300x112.webp","jetpack_featured_media_url":"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2024\/02\/Feature-Image-All-About-Loops-in-JavaScript-A-Comprehensive-Guide.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\/16"}],"replies":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/comments?post=42755"}],"version-history":[{"count":31,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/42755\/revisions"}],"predecessor-version":[{"id":90061,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/42755\/revisions\/90061"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/media\/43219"}],"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}]}}