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:
-
An array has a forEach method.
-
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.
-
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