Reputation: 5752
function stringifyObj(parmObj){
s="";
Object.getOwnPropertyNames(parmObj).forEach
(
function (val, idx, array) {
s+=val + ' -> ' + parmObj[val]+"\n";
}
)
return s;
}
var arrayOfObjects = [
{ name: 'Edward', value: 21 },
{ name: 'Sharpe', value: 37 }
];
console.log(
arrayOfObjects.forEach(function(parmArrItem)
{
const p=stringifyObj(parmArrItem);
console.log(p);
}
));
In the code below, 2 objects are displayed fine, but after that I get undefined
displayed at the end of the run. Where does the undefined
come from? Thanks.
Upvotes: 2
Views: 6081
Reputation: 48357
arrayOfObjects.forEach
returns nothing.
So, when you use console.log()
for a void function that's you received undefined.
forEach method only executes a callback provided function for every item from an array.
With the other words, the console
prints the result of evaluating an expression.
console.log()
is undefined since your function or expression not explicitly return something.
function stringifyObj(parmObj){
s="";
Object.getOwnPropertyNames(parmObj).forEach
(
function (val, idx, array) {
s+=val + ' -> ' + parmObj[val]+"\n";
}
)
return s;
}
var arrayOfObjects = [
{ name: 'Edward', value: 21 },
{ name: 'Sharpe', value: 37 }
];
arrayOfObjects.forEach(function(parmArrItem)
{
const p=stringifyObj(parmArrItem);
console.log(p);
}
);
Upvotes: 7