Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript function not returning true

I have the following js function and I'm pulling my hair out trying to determine why it won't return 'true'. I've verified the logic block is being hit by adding an alert into the block but it seems to skip the line containing the return statement.

function requiresMatchLevel(fields) {
        $.each(fields, function (i, field) {
            if (field.OperationParamName() == "MatchLevel" && field.Include()) {
                return true;
            }
        });
        return false;
    };
like image 353
user135498 Avatar asked Aug 21 '12 15:08

user135498


2 Answers

return acts on a per-function basis. Returning in the function passed to $.each will not have your outer function return something.

If you return something in the function passed to $.each, jQuery will receive the result. The only value that has effect here is false, which makes jQuery break out of the loop.

function requiresMatchLevel(fields) {
    var result = false;
    $.each(fields, function (i, field) {
        if (field.OperationParamName() == "MatchLevel" && field.Include()) {
            result = true;
            return false;  // break out of loop - no need to continue
        }
    });
    return result;
};
like image 146
pimvdb Avatar answered Sep 22 '22 09:09

pimvdb


How about

function requiresMatchLevel(fields) {
        var isMatch = false;
        $.each(fields, function (i, field) {
            if (field.OperationParamName() == "MatchLevel" && field.Include()) {
                isMatch = true;
            }
        });
        return isMatch;
    };
like image 30
Jan Avatar answered Sep 24 '22 09:09

Jan