usman saleem
usman saleem

Reputation: 160

function is returning undefined javascript

I wrote a function in javascript expression to check if the result is true or false but i am always getting undefined error

var array = [{
    email: '[email protected]',
    password: '123'
  },
  {
    email: '[email protected]',
    password: '123'
  }
];

let main = function(email, password) {

  return array.forEach((row) => {
    if (row.email === email && row.password === password) {
      return true

    } else {
      return false
    }
  });

};

var checkLogin = main('[email protected]', '123');
console.log(checkLogin)

checkLogin always return undefined

Upvotes: 1

Views: 104

Answers (5)

sunpietro
sunpietro

Reputation: 2099

The forEach array function doesn't return anything. If you touch looped array inside it then you are able to modify existing array without copying it.

Upvotes: 2

Usman Saleem
Usman Saleem

Reputation: 146

there's a problem with foreach. it doesn't return anything

var array = [
{email: '[email protected]', password: '123'},
];

let main = function(email, password) {

   for (var i = 0; i < array.length; i++) {
   if (array[i].email === email && array[i].password === password) {
    return true
     } 
       };
      return false
     };

   var checkLogin = main('[email protected]', '123');
   console.log(checkLogin) // returns true

Upvotes: 1

Sebastian Kaczmarek
Sebastian Kaczmarek

Reputation: 8515

It's because forEach does not return anything. You can use simple for-loop, like this:

var array = [
{email: '[email protected]', password: '123'},
{email: '[email protected]', password: '123'}
];

let main = function(email, password) {

    for (var i = 0; i < array.length; i++) {
        var row = array[i];
        if (row.email === email && row.password === password) {
            return true
        }
    }
    return false;
};

var checkLogin = main('[email protected]', '123');
console.log(checkLogin)

Also, take a look at some(), includes(), find() and findIndex()

Upvotes: 4

Nina Scholz
Nina Scholz

Reputation: 386519

You could take Array#some and return the result of the check.

var array = [{ email: '[email protected]', password: '123' }, { email: '[email protected]', password: '123' }];

let main = (email, password) =>
        array.some(row => row.email === email && row.password === password);

var checkLogin = main('[email protected]', '123');
console.log(checkLogin)

Upvotes: 0

Vinayak Shastri
Vinayak Shastri

Reputation: 29

there is something wrong with this logic:

return array.forEach((row) => {
if (row.email === email && row.password === password) {
  return true

} else {
  return false
}
});

without this logic it returns anything you want

Upvotes: 0

Related Questions