Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - ForEach

Tags:

javascript

I have a JavaScript array of objects. Something like this:

var people = [
  { id:1, firstName: 'Joe', lastName: 'Smith' },
  { id:2, firstName: 'Bill', lastName: 'Smith' }
];

I am iterating through the people using forEach. Here is my code:

function doSomething() {
  people.forEach(function(person, self) {
    self.helpPerson(person);
  }, this);
}

function helpPerson(person) {
  alert('Welcome ' + person.firstName);
}

I am trying to call helpPerson from within the forEach loop. However, when I attempt to call it, I get an error that says:

TypeError: self.helpPerson is not a function

If I add console.log(self);, "0" gets printed to the console window. This implies that I'm not passing in my parameter correctly. Or, I'm misunderstanding closures (just when I thought I fully understood it :)).

So, why doesn't self exit?

like image 840
Some User Avatar asked Apr 06 '26 23:04

Some User


1 Answers

You don't need to invoke helpPerson with a this, self, or any other context. Just invoke it directly:

var people = [
  { id:1, firstName: 'Joe', lastName: 'Smith' },
  { id:2, firstName: 'Bill', lastName: 'Smith' }
];

function doSomething() {
  people.forEach(function(person) {
    helpPerson(person);
  });
}

function helpPerson(person) {
  alert('Welcome ' + person.firstName);
}

When you log self to the console you are seeing "0" because it is printing the index of the loop iteration.

See the documentation for forEach to see what callbacks are passed to it's forEach function.

Typically, self is used to capture a context in a closure (var self = this;). Please see the related links to this question because that is a very important concept.

like image 52
Jonathan.Brink Avatar answered Apr 09 '26 15:04

Jonathan.Brink