lukkasz
lukkasz

Reputation: 133

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'

Upvotes: 4

Views: 1899

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115222

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);

Upvotes: 7

Nina Scholz
Nina Scholz

Reputation: 386578

You have two possibilities

A result set with Array#filter():

// return the result set
function test(name) {
    return people.filter(function(person){
        return person.name === 'John';
    });
}

or a boolean value if the given name is in the array with Array#some():

// returns true or false
function test(name) {
    return people.some(function(person){
        return person.name === 'John';
    });
}

Upvotes: 0

Related Questions