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?

4
  • 1
    You can also use return arr.some(el => el == value);. Or even simply return arr.includes(value). Commented Feb 20, 2022 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. Commented Feb 20, 2022 at 18:51
  • 3
    Because return applies to the enclosing function. Which is in jQuery case the (index, a) => {...} arrow function. Commented Feb 20, 2022 at 18:56
  • @Ivar okey, that is a fair answare, thanks Commented Feb 20, 2022 at 19:00

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.