1

I just want to check I'm doing this right. I have a variable bar that starts false and is set true if a function foo() returns false, however I check foo() against several arguments and don't want bar returning to false if it is ever set true. This is what I've written:

var bar = false;
var collection = []; // this is filled with arguments for foo
for(var i = 0; i < collection.length; i++) {
    bar = !foo(collection[i]) || bar;
}

Should that do the trick? Or is there maybe a simpler way?

4
  • 3
    Does "foo()" have side-effects that you want to happen for each member of the collection? Also, don't forget var for the variable "i" in the loop! Commented Mar 25, 2011 at 13:40
  • 1
    The question is a bit confusing, but by having bar in an OR like that you do guarantee that once true it will stay true. Both of pointy's points are good ones - mind, bar will most likely be out of foo's scope. Commented Mar 25, 2011 at 13:40
  • When you say "returning to false," do you mean "being set to false"? Variables do not return, only functions do. Commented Mar 25, 2011 at 13:40
  • 1
    Yes, I want foo() to execute for each array element. Have added var i! Also, yes I meant not be set to false after being set to true. Commented Mar 25, 2011 at 13:44

2 Answers 2

3

Change your for loop to do this and it should jump out as soon as it is set to true:

var bar = false;
var collection = []; // this is filled with arguments for foo
for(i = 0; i < collection.length && !bar; i++) {
    bar = !foo(collection[i]) || bar;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Don't forget the var declaration for "i"!
Yeah that's a good idea. Unfortunately in this case I need foo() to execute for every array element regardless.
@tamewhale In that case your code works fine. You can test things like this easily on jsfiddle - jsfiddle.net/s6qN3
I would swap the || part - the function is always executed. Unless you find this necessaty, bar || !foo... can be faster, depending on what kind of expensive things foo does.
0

I often use Array.maps() and Array.includes() for such things.

Array.map() runs a function on each item in the array and returns the value into a new array.

Array.includes() tests an array to see if it contains a value.

let collection = []; // this is filled with arguments for foo
let test = collection.map((currentItem) => {
  return foo(currentItem);
});
return test.includes(true);

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.