1
let database = [
  { username: "a1", password: "b1" },
  { username: "a2", password: "b2" },
];

let user = "a1";
let pass = "b1";


function isUserValid1(username, password) {
  for (let i = 0; i < database.length; i++) {
    if (
      database[i].username === username &&
      database[i].password === password
    ) {
      return true;
    }
  }
  return false;
}

function isUserValid2(username, password) {
  database.forEach(function (a) {
    if (
      a.username === username &&
      a.password === password
    ) {
      return true;
    }
  });
  return false;
}

console.log(isUserValid1(user, pass));
console.log(isUserValid2(user, pass));

I am learning javascript loops and I learnt that the For loop can be re-written as a forEach loop to get the same result in the above written way,but I am not getting the desired result from the function in which I have used forEach loop, i.e. function isUserValid2(). Please explain to me what is happening here.

  • The return statement that belongs to the anonymous function you pass to forEach does not belong to the isUserValid2 function. – Quentin Feb 20 '23 at 18:31
  • Its not the same as that question actually – Vatsa Pandey Feb 20 '23 at 18:52
  • His problem is that he's using forEach wrong in the second case, which results in the false, the same thing replicated as an array value works – Vatsa Pandey Feb 20 '23 at 18:55
  • Ok so what do I need to change in the isUserValid2 function so that it gives the same result as isUserValid1 function? – Sanjay Lamba Feb 20 '23 at 19:11
  • @SanjayLamba - Since, as the duplicate you say is a different question points out, `return` doesn't stop the loop you need to **not use `forEach`**. – Quentin Feb 20 '23 at 20:14
  • This for loop is a particular use of the for loop. It will (ab)use the `return` statement to halt the function execution and thus the for loop when the condition is met. This will hopefully not iterate over the whole list as would be expected from a for loop. The functional equivalent is the `array.some()` method, which will stop at the first "truthy" returned value. To do the other way, there is the `array.every()` method, which will stop at the first "falsy" returned value. – Kaiido Feb 22 '23 at 07:31

0 Answers0