0

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?

asked Sep 1, 2013 at 22:42
3
  • 8
    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. Commented Sep 1, 2013 at 22:45
  • Ahhh that makes sense - thank you! I was using document.write just for testing purposes. Commented Sep 1, 2013 at 22:48
  • 1
    You should use console.log instead for testing, it is vastly superior. Commented Sep 1, 2013 at 23:38

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.