Question: I have a question regarding this snippet of code. 

```js
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]);
  }
 },
 trim: names.forEach(function(name) {
  document.write(name)
  console.log(name)
 })
}

console.log("*********")
console.log(obj.prob());
console.log("*********")
```

If I run this code in my console I will get this:

```
John
Jen
Tony
*********
John
Jen
Tony
undefined
*********

```

That means that before my prob function that I call my trim function runs. Why is that? I didn't call it? Can I save it as a method on object and call it later when I need it?

Answer: 
### Explanation of this behaviour:

`obj.prob` is being assigned a *function declaration* and is **not** invoked.

`obj.trim` sets an call to the function `forEach`.

***This means when you are assign to the property you are also causing the code to run*** (this happens when you instantiate the`obj` object, which explains the initial logging of names)

---

### Suggested solution:

Wrap the invocation of `forEach` into an anonymous function declaration (just like you did with 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]);
          }
        },

  // the code in this function block will only run
  // when trim is invoked
  trim: function(){
         names.forEach(function(){
           document.write(name);
           console.log(name)
          });
       }
};

```
You just have to wrap your `each` function inside `function`

```js
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]);
  }
 },
 trim: function(){ names.forEach(function(name) {
        alert();
  document.write(name)
  console.log(name)
 })}
}

console.log("*********")
console.log(obj.prob());
console.log("*********")
```