Mutual recursion and JSLint - function was used before it was defined
Asked Answered
A

2

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);
};
Alphosis answered 22/8, 2017 at 2:34 Comment(5)
function isOdd(n) ...etc..Entasis
@JaromandaX JSLint still complains even if I use that formatAlphosis
it's to do with no-use-before-define option I guessEntasis
var isOdd; before var isEven = ... then remove var from your var isOddEntasis
You should remove JSLint from your computer, stab it in the heart, break it into little pieces, burn those pieces, and then bury them. It was never a good tool, and now it's obsolete.Nowhere
A
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);
    }
};
Alphosis answered 23/8, 2017 at 20:38 Comment(0)
A
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);
};

Activate answered 22/8, 2017 at 2:54 Comment(0)
A
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);
    }
};
Alphosis answered 23/8, 2017 at 20:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.