Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach loop and returning value of undefined

I was wondering if anyone could explain me why this function return undefined instead of founded object

var people = [
  {name: 'John'},
  {name: 'Dean'},
  {name: 'Jim'}
];

function test(name) {
  people.forEach(function(person){
    if (person.name === 'John') {
      return person;
    }   
  });
}

var john = test('John');
console.log(john);

// returning 'undefined'
like image 750
lukkasz Avatar asked Mar 14 '23 01:03

lukkasz


1 Answers

Returning into forEach loop won't work, you are on the forEach callback function, not on the test() function. So instead you need to return the value from outside the forEach loop.

var people = [{
  name: 'John'
}, {
  name: 'Dean'
}, {
  name: 'Jim'
}];

function test(name) {
  var res;
  people.forEach(function(person) {
    if (person.name === 'John') {
      res = person;
    }
  });
  return res;
}

var john = test('John');
console.log(john);

Or for finding a single element from array use find()

var people = [{
  name: 'John'
}, {
  name: 'Dean'
}, {
  name: 'Jim'
}];

function test(name) {
  return people.find(function(person) {
    return person.name === 'John';
  });
}

var john = test('John');
console.log(john);
like image 66
Pranav C Balan Avatar answered Mar 23 '23 09:03

Pranav C Balan