Consider this example:
var a = {
"Check" : function doThis(value, index, ar) {
if(value >= 10) {
document.write(value + ", ");
}
else {
document.write("The array element is less than 10, ");
}
}
}
var arr = [12, 20, 2, 3, 15];
document.write(arr.forEach(a.Check));
Which results in:
12, 20, The array element is less than 10,
The array element is less than 10, 15, undefined
I don't understand why there is an extra element in the array which is undefined. Does it have something to do with defining the callback function in an object?
1 Answer 1
replace:
document.write(arr.forEach(a.Check));
with:
arr.forEach(a.Check);
With document.write(arr.forEach(a.Check)); you are printing what the arr.forEach() call returns (undefined)
answered Sep 1, 2013 at 22:46
Pedro L.
7,6063 gold badges28 silver badges27 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
arr.forEach()doesn't have a return value, i.e. it "returns"undefined, which you're also writing. (Note the lack of a trailing comma behind it.) There is no extra element in the array, your code is buggy.document.writejust for testing purposes.console.loginstead for testing, it is vastly superior.