Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

forEach function inside the object

I have a question regarding this snippet of code.

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?

like image 310
Igor-Vuk Avatar asked Jan 30 '17 10:01

Igor-Vuk


People also ask

Can you do forEach on an object?

JavaScript's Array#forEach() function lets you iterate over an array, but not over an object. But you can iterate over a JavaScript object using forEach() if you transform the object into an array first, using Object. keys() , Object. values() , or Object.

Can you use forEach on an array of objects?

The forEach method is also used to loop through arrays, but it uses a function differently than the classic "for loop". The forEach method passes a callback function for each element of an array together with the following parameters: Current Value (required) - The value of the current array element.

What is the function of forEach ()?

The forEach() method is an iterative method. It calls a provided callbackFn function once for each element in an array in ascending-index order. Unlike map() , forEach() always returns undefined and is not chainable. The typical use case is to execute side effects at the end of a chain.

Can forEach be used in a variable?

The part of the foreach statement enclosed in parenthesis represents a variable and a collection to iterate. PowerShell creates the variable $<item> automatically when the foreach loop runs. Prior to each iteration through the loop, the variable is set to a value in the collection.


2 Answers

The names.forEach is called trying to assign the return value to trim. Putting it inside a function should work.

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) {
		document.write(name)
		console.log(name)
	})}
}

console.log("*********")
console.log(obj.prob());
console.log("*********")
console.log(obj.trim());
like image 126
skAstro Avatar answered Oct 18 '22 14:10

skAstro


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 theobj 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)
          });
       }
};
like image 30
Pineda Avatar answered Oct 18 '22 15:10

Pineda