Explanation of this behavior:
obj.prob assigned a function declaration and not called.
obj.trim sets up a call to the forEach .
This means that when you assign a property, you also call the code to run (this happens when you instantiate the obj object, which explains the initial registration of names)
Recommended Solution:
Include the forEach call in the anonymous function declaration (as in the for loop for the prob property):
var names = ["John", "Jen", "Tony"]; var obj = { prob: function () { for (var i = 0; i < names.length; i++) { document.write(names[i]); console.log(names[i]); } },
source share