1
var arr = ["1","2","3","4","5"];

function findValueInArrayJQ(array,value) {
  $.each(arr, (index, a) => {
    if(a == value) {
        return true;
    }
  });
  return false;  
}

function findValueInArrayJS(array,value) {
    for(let i = 0; i < array.length; i++) {
    if(array[i] == value)
        return true;
    }
    return false;
}

console.log(findValueInArrayJQ(arr,"1"));
console.log(findValueInArrayJS(arr,"1"));

Output

false
true

As far as I know both of them should give me the same output. Why the first one give me false output?

palloc
  • 323
  • 1
  • 9
  • 1
    You can also use `return arr.some(el => el == value);`. Or even simply `return arr.includes(value)`. – Ivar Feb 20 '22 at 18:44
  • Now I know that I have to make temp boolian variable and return with that. But why do I have to do that. – palloc Feb 20 '22 at 18:51
  • 3
    Because `return` applies to the enclosing function. Which is in jQuery case the `(index, a) => {...}` arrow function. – Ivar Feb 20 '22 at 18:56
  • @Ivar okey, that is a fair answare, thanks – palloc Feb 20 '22 at 19:00

0 Answers0