0

I'm trying to solve a simple algorithm where you evaluate that every number in an array is greater than the next one, so I first taught in the Every() method, but when I do a return is always false, but when I console.log() it display true!

How is this possible?

const arr = [3, 2, 1];

const returnRes = arr.every((value, index, arr) => value > arr[index + 1]);

const consoleLogRes = arr.every((value, index, arr) => console.log(value > arr[index + 1]));

console.log(returnRes);

Evidence

2
  • The every method only returns true if the test returns true for all items in the array. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jan 7, 2023 at 1:29
  • 3
    You have your return values mixed up. the true you see is the inner console.log() printing true once, and then the every terminates because console.log() returns undefined Commented Jan 7, 2023 at 1:57

2 Answers 2

1

At the third iteration. The value arr[index + 1] will be undefine. why? it because the value of arr[index + 1] will be arr(2+1) which is arr[3] and arr[3] does not exist because index start from zero not 1. what you can do is to add a check at the last iteration to prevent the undefine from happening. check the code below

const arr = [3, 2, 1];

const response = arr.every((value, index, arr) => {
   
  if (index + 1 === arr.length) {
    return true;
  }
  return value > arr[index + 1];
});

console.log(response);
Sign up to request clarification or add additional context in comments.

Comments

0

The issue is when your value is 1 and index is 2, that is, when the every function processes the last element of your array, arr[index + 1] returns undefined and 1 > undefined evaluates to false.

To properly fix it, you should return true when index is pointing to the last element:

const arr = [3, 2, 1];

const returnRes = arr.every((value, index, arr) =>
  index === arr.length - 1 || value > arr[index + 1]);

console.log(returnRes);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.