Help understanding the javaScript forEach method


#1

Hi,
I am attempting to understand the syntax used in the following example of JS code:

planets = [‘Mercury’,‘Venus’,‘Earth’,‘Mars’,‘Jupiter’,‘Saturn’,‘Uranus’,‘Neptune’,‘Pluto’]
planets.forEach(function(planet){
rootItem.addChild().topic = planet
})

I think the following three statements are correct:

  1. An array has a forEach method.

  2. That the forEach method allows a function to be called which is passed three values, the first being the item which is named planet in the code above.

  3. That the code of the function is being specified between the brace characters.

I am getting confused by the code function(planet), first is function a keyword or just a name? It seems that the function(planet) is both a definition and a call.

I looked at the W3 Schools tutorial and expanded the code snip to:

planets = [‘Mercury’,‘Venus’,‘Earth’,‘Mars’,‘Jupiter’,‘Saturn’,‘Uranus’,‘Neptune’,‘Pluto’]
planets.forEach(myfunction)
function myfunction(item,index,theArray){
rootItem.addChild().topic = item + " array index: " + index
}

To my mind my version is simpler to read and understand so I wonder if there are any advantages to using the first.

I apologise if all the above is simple and obvious but I am new to JS and braces.

Simon


#2

Ok I progressed further and entered the following:
planets = [‘Mercury’,‘Venus’,‘Earth’,‘Mars’,‘Jupiter’,‘Saturn’,‘Uranus’,‘Neptune’,‘Pluto’]
moons = [[],[],[“Moon”],[“Deimos”, “Phobos”],[“Ganymede”,“Callisto”,“Io”,“Europa”],[“Titan”,“Rhea”,“Iapetus”,“Dione”,“Tethys”,“Enceladus”],[“Titania”,“Oberon”,“Umbriel”,“Ariel”,“Miranda”],[“Triton”,“Proteus”],[“Charon”,“Hydra”,“Nix”]]

planets.forEach(function(planet,index){
NewRow = rootItem.addChild(null,function(NewRow){
NewRow.topic = planet
})
moons[index].forEach(function(moon){
NewRow.addChild().topic = moon
})
})

Then I rewrote it to try and make it simpler to understand:

planets = [‘Mercury’,‘Venus’,‘Earth’,‘Mars’,‘Jupiter’,‘Saturn’,‘Uranus’,‘Neptune’,‘Pluto’]
moons = [[],[],[“Moon”],[“Deimos”, “Phobos”],[“Ganymede”,“Callisto”,“Io”,“Europa”],[“Titan”,“Rhea”,“Iapetus”,“Dione”,“Tethys”,“Enceladus”],[“Titania”,“Oberon”,“Umbriel”,“Ariel”,“Miranda”],[“Triton”,“Proteus”],[“Charon”,“Hydra”,“Nix”]]

planets.forEach(addPlanet)

function addPlanet(planet,index) {
NewRow = rootItem.addChild()
NewRow.topic = planet
// now add the moons, from the array of arrays
moons[index].forEach(addMoons)
}

function addMoons(Moon){
NewMoon = NewRow.addChild()
NewMoon.topic = Moon
}

It works but I have the feeling that it should not. How does the function addMoons() have access to NewMoon. Also is NewMoon a variable or an object?

Simon