Thursday, November 20, 2025
HomeLanguagesJavascriptJavaScript Program to Print 1 to N using Recursion

JavaScript Program to Print 1 to N using Recursion

In this article, we will see how to print 1 to N using Recursion in JavaScript.

What is Recursion? 

The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. In the recursive program, the solution to the base case is provided and the solution to the bigger problem is expressed in terms of smaller problems. 

Examples:

Input : 5
Output : 1 2 3 4 5

Input : 10
Output : 1 2 3 4 5 6 7 8 9 10

Approach:

  • We create a function that takes two arguments: “num” which is the number up to which we have to print and “currentValue” which prints the current number.
  • Check for the base case. Here it is currentValue > num.
  • If the base condition is satisfied, then it returns and ends the recursion.
  • If the base condition is not satisfied, print currentValue and call the function recursively by increasing the currentValue by 1 and num, until the base condition satisfies.

 

Example: In this example, we will print 1 to N using Recursion in JavaScript.

Javascript




function printRecursiveNum(num,currentValue) {
    if (currentValue>num) {
        return;
    }
    console.log(currentValue);
    printRecursiveNum(num, currentValue + 1);
}
  
const num = 8;
printRecursiveNum(num,1);


Output

1
2
3
4
5
6
7
8

Time Complexity: O(N)

Space Complexity: O(N)

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32404 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6776 POSTS0 COMMENTS
Nicole Veronica
11925 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11994 POSTS0 COMMENTS
Shaida Kate Naidoo
6905 POSTS0 COMMENTS
Ted Musemwa
7160 POSTS0 COMMENTS
Thapelo Manthata
6861 POSTS0 COMMENTS
Umr Jansen
6846 POSTS0 COMMENTS