6

If I write the following code, JSLint complains that 'isOdd' was used before it was defined. Is there a way to write mutually recursive code and still please JSLint?

var isEven = function(n) {
    if (n === 0) {
        return true;
    }
    return isOdd(n - 1);
};

var isOdd = function(n) {
    if (n === 0) {
        return false;
    }
    return isEven(n - 1);
};
johnnyodonnell
  • 1,838
  • 3
  • 16
  • 34

2 Answers2

4

For JSLint, you have to add a global variables directive to the top of the file, so that it ignores usage of temporary "undefined" functions and variables.

/*global isOdd */

var isEven = function(n) {
    if (n === 0) {
        return true;
    }
    return isOdd(n - 1);
};

var isOdd = function(n) {
    if (n === 0) {
        return false;
    }
    return isEven(n - 1);
};

You could also declare isOdd at the top, but then you would change your actual code because a linting program doesn't understand hoisting:

var isOdd;

var isEven = function(n) {
    if (n === 0) {
        return true;
    }
    return isOdd(n - 1);
};

isOdd = function(n) {
    if (n === 0) {
        return false;
    }
    return isEven(n - 1);
};

Nano Miratus
  • 467
  • 3
  • 13
1

Converting these functions to methods of an object quell the error message from JSLint. This also does a better job of keeping the global namespace less polluted.

var numUtil = {
    isEven: function(n) {
        if (n === 0) {
            return true;
        }
        return this.isOdd(n - 1);
    },
    isOdd: function(n) {
        if (n === 0) {
            return false;
        }
        return this.isEven(n - 1);
    }
};
johnnyodonnell
  • 1,838
  • 3
  • 16
  • 34