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'
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With