I know that the below is perfectly viable:
var numberArray = [];
function addNumber(number) {
numberArray.push(number);
}
and then:
<input type="button" value="Save" onclick="addNum(10);">
<input type="button" value="Save" onclick="addNum(990);">
...
But is it possible, for a better code, to have both my array and my action on the same function, and then trigger it on a click event, thus populating my array? Asking because, doing this:
function addNumber(number) {
var numberArray = [];
numberArray.push(number);
}
Does not increase the array values.
I know that inline click events is considerate a bad practice nowadays, but it's for learning purposes. All other answers here reference the array as a global scope, which is what I'm trying to avoid.
Edit: Ok if the above is not possible, any answer avoiding the global scope usage is valid.
addNumberas a method, andnumberArrayas a property. To utilize one of these, you need to useaddEventListenerto attach events.addNumberwill no longer be global.window.addNumber = function...inside the IIFEaddEventListeneris a much better alternative.addNumberbeing global too, doesn't seem to bother you, one more alternative comes into mind. Functions are also objects, you could addnumberArrayas a property toaddNumber. Then refer it inaddNumber(or anywhere) like so:addNumber.numberArray.push(...). This way you can even keep the inline listeners.