Js for recursive function not working

My code in JS does not work, but c works. What for? Why doesn't For when calling a recursive function work? What can I do for a recursive function? I have to make this project using JavaScript.

Js code

<a onClick="req(1)">Click</a>
<script>
function req(s){
    if(s<5){
        console.log(s);
        for(i=0;i<s;i++){
            req(s+1);
        }
    }
}
</script>

This code returns this value: 1 2 3 4

C CODE

#include <stdio.h>

void req(int s){
    if(s<5){
        printf("%d\n",s);
        int i = 0;
        for(i = 0;i<s;i++){
            req(s+1);
        }
    }
}

void main(){
 req(1);

}

It:

1 2 3 4 4 4 3 4 4 4

+4
source share
1 answer

Is always. Announce. Your. Variables

Otherwise, they become global in sloppy mode.

function req(s) {
  if(s<10) {
    console.log(s);
    for(var i=0; i<s; i++) {
      req(s+1);
    }
  }
}
req(1);
Run codeHide result
+4
source

Source: https://habr.com/ru/post/1664762/


All Articles