It could be done by making arrayWords
and words
global variables, but thatās a very poor way of programming these days.
JavaScript is a functional language, and nesting functions to enjoy the benefits of what is called closure (which is the nesting of execution environments) is commonplace.
However, yes we can remove the returned function. Hereās how.
arrayWords
and the words
variable can be made global variables
arrayWords = ['site','point', 'test'];
words = document.getElementById("words");
This puts them at higher risk of being accidentally clobbered, and also allows users on the page to fiddle about with them too.
That leaves us with:
function openTrack(x) {
words.innerHTML = arrayWords[x];
}
...
amounttracks[i].onclick = openTrack(i);
But thereās a problem. If we execute the function right away, we will only have a return value from the function thatās assigned to the onclick event. So, we need to just assign the function to the onclick event instead.
The onclick event cannot pass values to the function, so the function will have to get the number from somewhere else. About the only useful place let at this stage is to store the number on the element that youāre tracking.
function openTrack(evt) {
var element = this;
var x = element.openTrackIndex;
words.innerHTML = arrayWords[x];
}
...
for (i = 0; i < amounttracks.length; i += 1) {
amounttracks[i].openTrackIndex = i;
amounttracks[i].onclick = openTrack;
}
This does result in making globally available the index value too, which is at risk of being clobbered or fiddled about with by anyone that happens to be looking.
So yes - it can be done without the nested function, but what you end up with is something that is a whole lot worse.
JavaScript is a functional language. Instead of staying with what you may be used to, it can help to learn more about the features of the language that youāre programming with.