

{"id":112690,"date":"2023-04-05T09:00:44","date_gmt":"2023-04-05T03:30:44","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=112690"},"modified":"2023-04-05T16:26:07","modified_gmt":"2023-04-05T10:56:07","slug":"loops-in-typescript","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/loops-in-typescript\/","title":{"rendered":"Loops in TypeScript"},"content":{"rendered":"<p>In TypeScript, loops are a way to execute a code block repeatedly until a specific condition is met. There are three main loops in TypeScript: the for loop, the while loop, and the do-while loop.<\/p>\n<p>The for loop is used when you know the exact number of times you want to loop. It consists of three parts: the initialization, the condition, and the iteration. The initialization is done only once at the beginning, the state is checked before each iteration, and the iteration is executed at the end of each iteration.<\/p>\n<p>The while loop is used when you want to loop while a specific condition is true. The state is checked before each iteration, and if it is true, the code block is executed. If it is false, the loop ends.<\/p>\n<p>The do-while loop is similar to the while loop, but the condition is checked at the end of each iteration instead of the beginning. This means that the code block is executed at least once, even if the state is false from the start.<\/p>\n<p>Loops are a powerful tool in TypeScript that allows you to automate repetitive tasks and process large amounts of data efficiently. However, it is essential to be careful when using loops to avoid infinite loops or other unintended consequences.<\/p>\n<h3>Definite and Indefinite Loops<\/h3>\n<p>In TypeScript, loops can be categorized as definite or indefinite, depending on whether the number of iterations is known.<\/p>\n<p>A definite loop is a loop where the number of iterations is known beforehand. The most common example of a definite loop is the for loop, where the number of iterations is specified in the loop&#8217;s initialization step. Definite loops are helpful when you know how many times you need to execute a code block and want to optimize the loop&#8217;s performance.<\/p>\n<p>An indefinite loop is a loop where the number of iterations is unknown beforehand. The most common example of an indefinite loop is the while loop, which continues as long as a specific condition is true. Indefinite loops are helpful when you don&#8217;t know in advance how many times you need to execute a block of code or when you want to keep looping until a certain condition is met.<\/p>\n<p>It is essential to be careful when using indefinite loops to avoid infinite loops or other unintended consequences. Infinite loops occur when the loop condition is never false, causing the loop to execute indefinitely and potentially crashing your program. To prevent this, it&#8217;s essential to ensure that the loop condition eventually becomes false or that there is a way to break out if needed.<\/p>\n<h3>For Loops in TypeScript<\/h3>\n<p>A for loop is used to run a block of code repeatedly. It is frequently used to loop through an array or other objects. Similar to JavaScript&#8217;s for loop, a for loop in TypeScript has the following syntax:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">for (initialization; condition; increment) {\r\n \/\/ code to be repeated\r\n}\r\n<\/pre>\n<p>The initialization statement, which is used to establish a variable&#8217;s initial value, is run before the loop begins. Before beginning each iteration of the loop, the condition statement is assessed to determine if the loop should continue. Each iteration ends with the increment statement being executed. The value of the variable used in the condition statement is usually updated using it.<\/p>\n<p>Here&#8217;s an example of a for loop in TypeScript that iterates over an array of numbers and calculates their sum:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const DataFlair_numbers = [1, 2, 3, 4, 5];\r\nlet sum = 0;\r\n\r\n\r\nfor (let i = 0; i &lt; DataFlair_numbers.length; i++) {\r\n sum += DataFlair_numbers[i];\r\n}\r\n\r\n\r\nconsole.log(sum);\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">15<\/div>\n<p>In this illustration, the loop begins with i= 0 and runs until I fall below the length of the DataFlair_numbers array. The sum variable is increased with the value of the current array element on each iteration.<\/p>\n<h3>Types of For Loop<\/h3>\n<p>In TypeScript, the for loop is a type of loop that allows you to execute a block of code a specified number of times. The for loop has three parts: the initialization, the condition, and the iteration.<\/p>\n<p>There are two types of for loops in TypeScript: the traditional for loop and the for&#8230;of the loop.<\/p>\n<p>The traditional loop is used when you know the exact number of times you want to loop. It consists of three parts: the initialization, the condition, and the iteration. The initialization is done only once at the beginning, the condition is checked before each iteration, and the iteration is executed at the end of each iteration. Here is an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">for (let DataFlair_i  = 0; DataFlair_i  &lt; 10; DataFlair_i ++) {\r\n console.log(DataFlair_i );\r\n}\r\n<\/pre>\n<p><strong>Output<\/strong> &#8211;<\/p>\n<div class=\"code-output\">0<br \/>\n1<br \/>\n2<br \/>\n3<br \/>\n4<br \/>\n5<br \/>\n6<br \/>\n7<br \/>\n8<br \/>\n9<\/div>\n<p>This loop will execute 10 times and print the numbers from 0 to 9 to the console.<\/p>\n<p>The for&#8230;of the loop is used when you want to loop over the elements of an array or an iterable object. It was introduced in ECMAScript 6 and is supported in TypeScript. Here is an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const DataFlair_arr = [1, 2, 3, 4, 5];\r\nfor (const item of DataFlair_arr) {\r\n console.log(item);\r\n}\r\n<\/pre>\n<p><strong>Output<\/strong>&#8211;<\/p>\n<div class=\"code-output\">1<br \/>\n2<br \/>\n3<br \/>\n4<br \/>\n5<\/div>\n<p>This loop will iterate over each element of the array arr and print it to the console.<\/p>\n<p>Both types of for loops are useful in different situations, and it&#8217;s important to choose the right type of loop for your needs. The traditional for loop is best when you know the exact number of iterations, while the for&#8230;of loop is best when you need to iterate over the elements of an array or an iterable object.<\/p>\n<h3>While Loops in TypeScript<\/h3>\n<p>While a specific condition is true, a code block is repeated using a while loop. Following syntax:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">while (condition) {\r\n \/\/ code to be repeated\r\n}\r\n<\/pre>\n<p>The condition statement is evaluated before each iteration of the loop and determines whether the loop should continue or not.<\/p>\n<p>Here&#8217;s an example of a while loop in TypeScript that generates random numbers until a number greater than 0.5 is generated:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">let DataFlair_randomNumber = Math.random();\r\n\r\n\r\nwhile (DataFlair_randomNumber &lt;= 0.5) {\r\n console.log(DataFlair_randomNumber);\r\n DataFlair_randomNumber = Math.random();\r\n}\r\n\r\n\r\nconsole.log(DataFlair_randomNumber);\r\n<\/pre>\n<p>In this illustration, the loop begins with a number that is chosen at random and runs until it reaches a value of less than or equal to 0.5. A new random number is created and verified after each iteration.<\/p>\n<h3>Do-While Loops in TypeScript<\/h3>\n<p>Like a while loop, a do-while loop executes the code block at least once before checking the condition. A do-while loop in TypeScript has the following syntax:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">do {\r\n \/\/ code to be repeated\r\n} while (condition);\r\n<\/pre>\n<p>Here&#8217;s an example of a do-while loop in TypeScript that asks the user to enter a number until a positive number is entered:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">let DataFlair_number;\r\n\r\n\r\ndo {\r\n DataFlair_number = prompt('Enter a positive number:');\r\n} while (DataFlair_number &lt;= 0);\r\n\r\n\r\nconsole.log(DataFlair_number);\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">2<\/div>\n<p>In this instance, the loop asks the user to enter a DataFlair_number at the outset. The loop will continue if the joined DataFlair_number is less than or equal to 0. A positive DataFlair_number causes the loop to end, and the entered DataFlair_number to be shown.<\/p>\n<h3>Loop Control Statements<\/h3>\n<p>In addition to the basic loop types, TypeScript also supports several loop control statements that allow you to control the flow of a loop.<\/p>\n<h4>Break<\/h4>\n<p>Use the break statement to end a loop right away. When it is run, the loop is broken, and the program moves on to the code following the loop. Here is an illustration of how to use a for loop&#8217;s break statement to end the loop when a specific condition is satisfied:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const DataFlair_numbers = [1, 2, 3, 4, 5];\r\nlet sum = 0;\r\n\r\n\r\nfor (let i = 0; i &lt; DataFlair_numbers.length; i++) {\r\n if (sum &gt;= 10) {\r\n   break;\r\n }\r\n sum += DataFlair_numbers[i];\r\n}\r\n\r\n\r\nconsole.log(sum);\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">10<\/div>\n<p>The loop in this illustration adds up an array of numbers iteratively until the total is more than or equal to 10. When this criterion is satisfied, the break statement is carried out, which ends the loop.<\/p>\n<h4>Continue<\/h4>\n<p>Use the continue statement to continue with the next loop iteration while skipping the current one. When it is run, the loop skips the remaining words and moves on to the following iteration. Here is an illustration of how to skip even numbers in a for loop using the continue statement:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const DataFlair_numbers = [1, 2, 3, 4, 5];\r\nlet sum = 0;\r\n\r\n\r\nfor (let i = 0; i &lt; DataFlair_numbers.length; i++) {\r\n if (DataFlair_numbers[i] % 2 === 0) {\r\n   continue;\r\n }\r\n sum += DataFlair_numbers[i];\r\n}\r\n\r\n\r\nconsole.log(sum);\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">9<\/div>\n<p>In this example, the loop iterates over an array of numbers and skips even numbers using the continue statement.<\/p>\n<h3>Conclusion<\/h3>\n<p>Programming requires loops, and TypeScript offers a variety of methods to employ them. While the while and do-while loops repeat a block of code as long as a condition is true, the for loop iterates through a set of elements. Moreover, TypeScript offers loop control statements like break and continue, which let you manage a loop&#8217;s progress. Create TypeScript code that is more effective and manageable by utilizing loops and control statements.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In TypeScript, loops are a way to execute a code block repeatedly until a specific condition is met. There are three main loops in TypeScript: the for loop, the while loop, and the do-while&#46;&#46;&#46;<\/p>\n","protected":false},"author":581,"featured_media":112976,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27319],"tags":[27346],"class_list":["post-112690","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-typescript-tutorials","tag-loops-in-typescript"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Loops in TypeScript - DataFlair<\/title>\n<meta name=\"description\" content=\"There are three main loops in TypeScript: the for loop, the while loop, and the do-while loop. Learn more about these with exqamples.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/loops-in-typescript\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Loops in TypeScript - DataFlair\" \/>\n<meta property=\"og:description\" content=\"There are three main loops in TypeScript: the for loop, the while loop, and the do-while loop. Learn more about these with exqamples.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/loops-in-typescript\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-04-05T03:30:44+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-04-05T10:56:07+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/typescript-loop.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"7 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Loops in TypeScript - DataFlair","description":"There are three main loops in TypeScript: the for loop, the while loop, and the do-while loop. Learn more about these with exqamples.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/loops-in-typescript\/","og_locale":"en_US","og_type":"article","og_title":"Loops in TypeScript - DataFlair","og_description":"There are three main loops in TypeScript: the for loop, the while loop, and the do-while loop. Learn more about these with exqamples.","og_url":"https:\/\/data-flair.training\/blogs\/loops-in-typescript\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2023-04-05T03:30:44+00:00","article_modified_time":"2023-04-05T10:56:07+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/typescript-loop.webp","type":"image\/webp"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"7 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/loops-in-typescript\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/loops-in-typescript\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445"},"headline":"Loops in TypeScript","datePublished":"2023-04-05T03:30:44+00:00","dateModified":"2023-04-05T10:56:07+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/loops-in-typescript\/"},"wordCount":1322,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/loops-in-typescript\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/typescript-loop.webp","keywords":["loops in typescript"],"articleSection":["TypeScript Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/loops-in-typescript\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/loops-in-typescript\/","url":"https:\/\/data-flair.training\/blogs\/loops-in-typescript\/","name":"Loops in TypeScript - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/loops-in-typescript\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/loops-in-typescript\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/typescript-loop.webp","datePublished":"2023-04-05T03:30:44+00:00","dateModified":"2023-04-05T10:56:07+00:00","description":"There are three main loops in TypeScript: the for loop, the while loop, and the do-while loop. Learn more about these with exqamples.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/loops-in-typescript\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/loops-in-typescript\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/loops-in-typescript\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/typescript-loop.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/typescript-loop.webp","width":1200,"height":628,"caption":"typescript loop"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/loops-in-typescript\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"TypeScript Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/typescript-tutorials\/"},{"@type":"ListItem","position":3,"name":"Loops in TypeScript"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam6\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/112690","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/581"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=112690"}],"version-history":[{"count":7,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/112690\/revisions"}],"predecessor-version":[{"id":113927,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/112690\/revisions\/113927"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/112976"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=112690"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=112690"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=112690"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}