[javascript] Break statement in javascript array map method

Possible Duplicate:
How to short circuit Array.forEach like calling break?

Is there a way so that I can break out of array map method after my condition is met ? I tried the following which throws "Illegal Break Statement" Error. This is some random example I came up with.

var myArray = [22,34,5,67,99,0];

var hasValueLessThanTen = false;

myArray.map(function (value){
    if(value<10){
      hasValueLessThanTen = true;
      break;
    }
  }
);

We can do using for loops, but I wanted to know whether we can accomplish the same using map method ?

This question is related to javascript

The answer is


That's not possible using the built-in Array.prototype.map. However, you could use a simple for-loop instead, if you do not intend to map any values:

var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
  if (myArray[i] < 10) {
    hasValueLessThanTen = true;
    break;
  }
}

Or, as suggested by @RobW, use Array.prototype.some to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:

var hasValueLessThanTen = myArray.some(function (val) { 
  return val < 10;
});