Mathew
Mathew

Reputation: 1450

js recursive function changing variables unexpectedly

Here is a function I wrote in Javascript to illustrate the problem I'm having.

function test(x,depth){
    for (n=0;n<x;n++){
        console.log(x.toString()+" "+depth.toString()+" "+n.toString())
        test(x-1,depth+1)
        console.log(x.toString()+" "+depth.toString()+" "+n.toString())
    }
}


test(4,0)

here is my console output:

4 0 0  
3 1 0  
2 2 0
1 3 0
1 3 0
2 2 1
3 1 2
4 0 3

why is the variable n effected by calling test(x-1,depth+1)? n is not passed as a parameter.

Thanks

Upvotes: 0

Views: 47

Answers (2)

Suren Srapyan
Suren Srapyan

Reputation: 68665

Your n is a global variable because it is declared without let, var or const. It is actually window.n. Means that each recursive called function uses the single property. Declare it via let or var to make each function has its own n variable.

function test(x,depth){
    for (let n = 0; n < x; n++){
        console.log(x.toString()+" "+depth.toString()+" "+n.toString())
        test(x-1,depth+1)
        console.log(x.toString()+" "+depth.toString()+" "+n.toString())
    }
}


test(4,0)

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074545

n is global, created via The Horror of Implicit Globals* the first time you assign a value to it (n=0), and so that one global variable is used by all calls to test. You need to declare it within test for it to be local (and thus for each call to have its own copy). (E.g., add var or, in ES2015+, let.)


* (That's a post on my anemic little blog.)

Upvotes: 3

Related Questions