Skip to content Skip to sidebar Skip to footer

Foreach Return Object Property Javascript

In the following code, can somebody explain why object property is returned using a for loop but not using a forEach. Is it something related to returning object references or is i

Solution 1:

return returns to the function it's in. In the for.. example, that's searchAge. When you use forEach(), you pass it a callback function, and so you return the value to that callback. You never return anything in searchLocation.

You should just use the regular for.. loop both times here.

Solution 2:

in java script there is no break method for forEach.

if you use

return obj.location

it has no effect on it

but when you use return method in for loop then that will break and return the value.

There is some and every which has a break method.

Some break on return true and every break on return false;

try like this

var location = "";
empArray.some(function (obj) {
    if (name === obj.name) {
        location = obj.location;
        returntrue;
    }
});
return location;

Or try like this

var location = "";
empArray.every(function (obj) {
    if (name === obj.name) {
        location = obj.location;
        returnfalse;
    }
});.
return location;

Solution 3:

That is because in the bellow code snippet

var searchLocation = function(name){
    empArray.forEach(function(obj){
        if(name === obj.name) {
            return obj.location;
        }
    });
};

If you want to do the same thing use filter like bellow

var searchLocation = function(name){
   return empArray.filter(function(obj) {
      return name === obj.name
   })[0].location;
};

the return statement will be for anonymous function you are giving as parameter to foreach function not to function searchLocation.

Solution 4:

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

forEach() executes the callback function once for each array element; unlike every() and some(), it always returns the value undefined.

So you could try this which sets a variable and returns it after the loop:

var searchLocation = function(name){
    var result;
    empArray.forEach(function(obj){
        if(name === obj.name) {
            result =  obj.location;
        }
    });
    return result;
};

Post a Comment for "Foreach Return Object Property Javascript"