How can I target an Adobe Illustrator script to limit itself to the user's selection if anything is selected, or to run on all objects if nothing is selected?
app.activeDocument.selection
is often used to target the current selection but is empty if there's no selection.
app.activeDocument.pageItems
is where to access all items as if everything was selected. So, this one liner:
var scope = app.activeDocument.selection.length ? app.activeDocument.selection : app.activeDocument.pageItems;
...sets the variable scope
to be the selection if there is one, or everything if there is none. Its contents can then be cycled through the normal way, for example:
for(var i=0;i<scope.length;i++){
// do things with scope[i]
}