Skip to main content
dublove
Legend
August 23, 2026
Question

When selecting multiple objects to call a function, is an inner loop better or an outer loop better?

  • August 23, 2026
  • 1 reply
  • 26 views

For example, I select multiple objects, and then call functions that are suitable for the content of the framework.
There are two ways, which one is more efficient (more scientific)?

var d = app.activeDocument;
var item = d.selection[0];
var items = d.selection;
var sel = items;

// 00001 outer loop
for (var i = 0; i < sel.length; i++) {
frameFitToContent(sel[i])
}
function frameFitToContent(s) {
s.fit(FitOptions.FRAME_TO_CONTENT);
}

// 00002 internal circulation----
frameFitToContent(items);
function frameFitToContent(sel) {
for (var i = 0; i < sel.length; i++) {
sel[i].fit(FitOptions.FRAME_TO_CONTENT);
}
}

 

    1 reply

    rob day
    Community Expert
    Community Expert
    August 23, 2026

    Hi ​@dublove , In the first example I don’t think you need a function or the item and sel variables—it could simply be:


    var items = app.activeDocument.selection;
    // 00001 outer loop
    for (var i = 0; i < items.length; i++) {
    items[i].fit(FitOptions.FRAME_TO_CONTENT);
    }

     

    A function makes more sense if you include the loop, maybe do some error checking, and want to call the function multiple times within a script.

     

    Here I don’t need any variables, I just pass in app.activeDocument.selection, and check if there is a selection, and if there is, does it take the fit method—this would still break with a selection that has groups or nested text frames:

    // 00002  internal circulation----
    frameFitToContent(app.activeDocument.selection);
    function frameFitToContent(sel) {
    if (sel.length > 0) {
    for (var i = 0; i < sel.length; i++) {
    try {
    sel[i].fit(FitOptions.FRAME_TO_CONTENT);
    }catch(e) {alert("No Fit Options")}
    }
    }else {{alert("No Selection")}}
    }