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 it something specific to forEach loop on an array ?
var empModule = (function(){
var empArray = [{
"name":"Aish",
"age":"27",
"location": "All"
},{
"name":"Anu",
"age":"26",
"location": "Muz"
},{
"name":"Vern",
"age":"25",
"location": "Mang"
}];
var searchAge = function(name){
for(var i=0;i<empArray.length;i++) {
if(empArray[i].name === name) {
return empArray[i].age;
}
};
};
var searchLocation = function(name){
empArray.forEach(function(obj){
if(name === obj.name) {
return obj.location;
}
});
};
return {
findAge: searchAge,
findLocation: searchLocation
};
})();
var secAge = empModule.findAge("Anu");
console.log(secAge); // Correct Output
var thirdLoc = empModule.findLocation("Vern");
console.log(thirdLoc); // Returns undefined
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.
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;
return true;
}
});
return location;
Or try like this
var location = "";
empArray.every(function (obj) {
if (name === obj.name) {
location = obj.location;
return false;
}
});.
return location;
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