Introduction

A recursive function is a function that calls itself, in other words, multiple times. The advantage of using recursion is code reusability. A recursive function must have at least one exit condition that can be satisfied.
In the following example, we will display 100 numbers without a loop but using a recursive function instead.

Complete Program

app.ts
  1. class Number_Without_Loop
  2. {
  3. Display_Number(num: number)
  4. {
  5. if (num <= 100)
  6. {
  7. var span = document.createElement("span");
  8. span.style.color = "blue";
  9. span.innerText = num + ",";
  10. document.body.appendChild(span);
  11. this.Display_Number(num + 1);
  12. }
  13. }
  14. }
  15. window.onload = () =>
  16. {
  17. var obj = new Number_Without_Loop();
  18. obj.Display_Number(1);
  19. };
default.htm
  1. <!DOCTYPE html>
  2. <html lang="en"
  3. xmlns="http://www.w3.org/1999/xhtml">
  4. <head>
  5. <meta charset="utf-8" />
  6. <title>TypeScript HTML App</title>
  7. <link rel="stylesheet" href="app.css" type="text/css" />
  8. <script src="app.js"></script>
  9. <style type="text/css"></style>
  10. </head>
  11. <body>
  12. <h3>Display 100 Number Without Loop In TypeScript</h3>
  13. <p></p>
  14. </body>
  15. </html>
app.js
  1. var Number_Without_Loop = (function() {
  2. function Number_Without_Loop() {}
  3. Number_Without_Loop.prototype.Display_Number = function(num) {
  4. if (num <= 100) {
  5. var span = document.createElement("span");
  6. span.style.color = "blue";
  7. span.innerText = num + ",";
  8. document.body.appendChild(span);
  9. this.Display_Number(num + 1);
  10. }
  11. };
  12. return Number_Without_Loop;
  13. })();
  14. window.onload = function() {
  15. var obj = new Number_Without_Loop();
  16. obj.Display_Number(1);
  17. };
Output
Result.jpg
For more information, download the attached sample application.