Is it possible to write this “singleton array declaration” even shorter? There are different scripts which adds something to array but they’re loaded asynchronously, so I don’t know which will initialize array first.
var array = array || [];
array.push("foo");
console.debug(array[0]);
I tried something like this but this doesn’t work:
(array || []).push("foo");
Any suggestions?
If you need to preserve the existing variable (which would happen if you don’t know which piece of code will execute first), your code can’t be written any shorter.
Of course, you can change the default value if you want:
But if the variable already exists, it won’t add
fooanymore. Probably not what you want.Old answer
With your given example: