Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to use global variables in recursion

I'm helping someone on his school assignment - we're trying to write recursive function (if it matters - either in PHP or JavaScript).

I understand principles of recursion quite well, but I haven't wrote any of those from "academic" viewpoint.

Is it good practice to use global variable to store result, something like:

var results = [];

var rec = function(a) {
    ...
    if (match)
        results.push(someValue);
}

Or should I use return for collecting all those results back together (which would be much more difficult)?

like image 495
user1702401 Avatar asked Feb 12 '23 17:02

user1702401


2 Answers

It is good practice to use as little global variables as possible, preferrably none1.

To avoid the need for a global variable in recursion, you can use an inner function that uses a closure:

var rec = function(a) {
    var someValue = [];
    function dorec() {
      // stuff happens
      if (match)
        results.push(someValue);
      }
    }
    dorec();  
}

1Douglas Crockford states

All variables should be declared before used. JavaScript does not require this, but doing so makes the program easier to read and makes it easier to detect undeclared variables that may become implied globals. Implied global variables should never be used. Use of global variables should be minimized.

like image 120
KooiInc Avatar answered Feb 14 '23 05:02

KooiInc


To expand on the existing comments and to give you a concrete example, here is the code for recursively adding the even numbers to the given array:

var match;
var rec = function(a, res) {
    if (a < 0) {
        return res;
    }

    match = a % 2 == 0;

    if (match) {
        res.push(a);
    }
    return rec(a - 1, res);
}

var results = rec(10, []);

alert(results);

and the fiddle: http://jsfiddle.net/xukukggL/

like image 25
Liam Avatar answered Feb 14 '23 07:02

Liam