1

This javascript should run the function func len times and then return whether it was successful all the times or not. Instead, the for loop is cancelled as soon as func returns false. How can this be explained? (jsfiddle)

function do_something(func, len) {
    var res = true;
    for (var i = 0; i < len; i++) {
        res = res && func(i);
    }
    return res == true;
}

do_something(function(x) {
    console.log(x);
    return false;
}, 5);

do_something(function(x) {
    console.log(x);
    return true;
}, 5);

I would expect 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, but the output looks like this:

0
0
1
2
3
4
2
  • Pedantic: You could just return res instead of returning res == true Commented Mar 10, 2016 at 19:44
  • That might return undefined in some cases and doesn't solve the problem. Commented Mar 10, 2016 at 19:45

1 Answer 1

8

Because the first function returns false, res = res && func(0) will assign false to res. The next time the line is executed, i.e. res = res && func(1), func(1) won't be executed because res is (and stays) false.

&& is short-circuiting. Given a && b, if a evaluates to false, b won't be evaluated at all.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.