Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Javascript – creating "some" function

Trying to create "some" function. i.e., return true if any of the elements in teh array satisfies the condition

function some(array, predicate) {
 for (var i = 0; i < array.length; i++) {
 if (predicate(array[i]))
 return true;
 }
 return false;
}
console.log(some([NaN, 3, 4], isNaN));
// → true
console.log(some([2, 3, 4], isNaN));
// → false

Question 1: Above is the solution in the book and I'm not sure why "return false" would overwrite "return true" in every case. The above solution seems to suggest that "return false" will be run only if "return true" was never run – WHY??

My solution looked like this.

var some = function(array, condition) {
 var answer = false;
 for(var i=0; i<array.length; i++) {
 if(condition(array[i])) {answer = true}; 
 }
 return answer
};

Question 2: Is the book solution better because it takes less memory (ie the "answer" variable)?

Thanks!

Answer*

Draft saved
Draft discarded
Cancel
1
  • I feel like my English is terrible in that answer, suggest me an edit if you know how to "word" it better. Commented May 6, 2015 at 19:34

lang-js

AltStyle によって変換されたページ (->オリジナル) /