JavaScript recursion

 In JavaScript when a function calls itself it's called as recursion. We use recursion to make code shorter.

Let's assume we want to count numbers from 0 to 10. We could achieve this using a for loop. However, we have to write it over and over as needed to do a simple task. Instead we could use a recursive function that does the same.

Take a look at the example to understand this better. In the first instance, we used a loop. In the second instance we've a recursive function called countTill() that does the same thing flexibly.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Recursion</title>
</head>
<body>
    <script>
        //without recursion count from 0 to 10
        for (var i = 0i < 10i++) {
            document.write(i);
        }
        document.write("<hr>")
        //Count with recursion
        function countTill(n) {
            document.write(n);
            if (n < 9)
                countTill(n+1);
            }
        countTill(0);
    </script>
</body>
</html>



Post a Comment

0 Comments

React