0

I'm trying to create a simple function that checks to see if all of the items in an array are in order, but it's giving me a bit of unwanted behavior. I've come up with this:

const isArrayInOrder = (array) => {
  let lowNum = Number.NEGATIVE_INFINITY;
  array.forEach((element, index) => {
    if (element < lowNum) {
      console.log("False");
      return false;
    }

    lowNum = element;
  });
  console.log("True!");
  return true;
};

let testArray = [1, 2, 3, 4, 7, 11, 22, 31, 800];
isArrayInOrder(testArray);

let testArray2 = [-800, -30, -5, 0, 10, 55, 200, 2000, 1999];
isArrayInOrder(testArray2);

Calling isArrayInOrder() with testArray returns true, as expected.

Calling isArrayInOrder() with testArray2 returns false, but then goes on to unexpectedly execute the console.log("True!") command at the bottom of the function.

It seems to me once return false is hit that should be the end of the function, right? So how is it making it to this second console.log?

Raydot
  • 1,458
  • 1
  • 23
  • 38
  • 1
    The `.forEach()` method completely ignores returned values. The `return` statement exits **one** function, the one that most immediately contains it. – Pointy Jun 01 '20 at 23:50

1 Answers1

1

You need to understand that return will return to the inner function.

So if you do:

const outerFunction = () => {
    const innerFunction = () => {
        return 'inner';
    }

    console.log(innerFunction()); // outputs 'inner';

     return 'outer';
}

console.log(outerFunction()); // outputs 'outer';

What you are looking for is Array.prototype.every():

const isArrayInOrder = (array) => {
  let lowNum = Number.NEGATIVE_INFINITY;
  return array.every((element, index) => {
    if (element < lowNum) {
      return false;
    } else {
      lowNum = element;
      return true;
    }
  });
};
Elias Soares
  • 9,884
  • 4
  • 29
  • 59
  • I'll be a pickled goose, I did not know that. I suspected the closure had something to do with it. Thank you @Elias. – Raydot Jun 02 '20 at 00:03