Hasan Delibaş
Hasan Delibaş

Reputation: 500

js for in recursive function not working

My Code is in JS not working but in c is working. Why? Why For in calling recursive function not working? What can i do for in recursive function? I must make this project with 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 return 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 is :

1 2 3 4 4 4 3 4 4 4

Upvotes: 4

Views: 396

Answers (1)

Oriol
Oriol

Reputation: 288550

Always. Declare. 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);

Upvotes: 4

Related Questions