0

For example:

  function findIndexOfFirstNonNegative(array) {
    array.forEach( (a, i) => { if (a >= 0) { return i; }});
    return null;
  }

it turns out the return i; will not return to the caller of the function findIndexOfFirstNonNegative(), but it will return from the fat arrow function and let the forEach go on (or even if it is a plain old function instead of fat arrow function, it is the same).

Is there a way to break out and return to the caller?

nonopolarity
  • 146,324
  • 131
  • 460
  • 740
  • 2
    [how to stop Javascript forEach?](//stackoverflow.com/q/6260756), [How to short circuit Array.forEach like calling break?](//stackoverflow.com/q/2641347) – Tushar Apr 26 '17 at 07:39
  • 2
    You using the wrong method if you wish to find an index of an item. `findIndex` may be better. See [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Iteration_methods) for full list. – ste2425 Apr 26 '17 at 07:41
  • 1
    You may want to use Array.some for more general purposes. https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/some – FitzFish Apr 26 '17 at 07:44
  • @Cobaltway `Array.some` will just return true or false – Weedoze Apr 26 '17 at 07:47
  • @Weedoze You can use it to break the loop by returning true. – FitzFish Apr 26 '17 at 07:49
  • 2
    The term "fat arrow function" is obsolete. The correct term is "arrow function". –  Apr 26 '17 at 07:49
  • @torazaburo is it obsolete since when... since 2 weeks ago? (just kidding) – nonopolarity Apr 26 '17 at 09:32
  • 1
    At least since the spec was published two years ago. –  Apr 26 '17 at 09:44

2 Answers2

4

You can use findIndex in Javascript instead

array.findIndex( a => a >= 0);

console.log([-5,-10, 0, 4].findIndex( a => a >= 0))
taile
  • 2,738
  • 17
  • 29
1

Use a classical loop. This will return to the function when the condition is met.

I added a console.log() inside the loop to show that it will stop after founding the non negative number

function findIndexOfFirstNonNegative(array) {
  for (let i = 0, l = array.length; i < l; i++) {
    console.log("Loop item : " + array[i] + " at index " + i);
    if (array[i] >= 0) return i;
  }
  return -1;
}

console.log("Index found : " + findIndexOfFirstNonNegative([-5, 2, 1]))

OR

You can directly use Array#findIndex()

function findIndexOfFirstNonNegative(array) {
  return array.findIndex(a=>a>=0);
}

console.log("Index found : " + findIndexOfFirstNonNegative([-5, 2, 1]))
Weedoze
  • 13,683
  • 1
  • 33
  • 63