Home > other >  Javascript every() display different value when doing a return and console.log()
Javascript every() display different value when doing a return and console.log()

Time:01-08

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

CodePudding user response:

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) =>
  value > arr[index   1] || index === arr.length - 1);

console.log(returnRes);

CodePudding user response:

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);
  • Related