Skip to content
Advertisement

The return false in jquery each loop not end the entire function

It seems that the return word in jquery each loop will not end the entire function. Here is the code below. The purpose is, when a value in the array is not a number, it should stop all the function, not only the loop. But it turns out that it will only stop the loop and contiue the other logic below.

In C# or Java, the return word will stop the entire function. Is not desgined like this in JavaScript?

function testMehtod() {
        var itemIds = [];
        $("#confirmOrderItemContainer").find(":checkbox:checked").each(function (i, o) {
            itemIds[i] = $(o).attr('item-id');
            if (isNaN(itemIds[i])) {
                return false;
            } 
        });

        //other logic ...
}

Advertisement

Answer

if you need to catch breaking the loop and return false too:

function testMehtod() {
    var itemIds = [];
    var ret = true; // our flag variable with default value - everything is good
    
    $("#confirmOrderItemContainer").find(":checkbox:checked").each(function (i, o) {
        itemIds[i] = $(o).attr('item-id');
        if (isNaN(itemIds[i])) { // not good
            ret = false; // let set flag about it
            return false; // break $.each loop
        } 
    });
    if (ret === false) { // not good? let's leave function
        return false;
    }

    //other logic ...
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement