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?