Incrementing Your Own Loop Variable

Controlling your own loop in n8n can get a little tricky because you have to use values from nodes that are in scope before the loop (initialized) AND within the loop (updated/incremented).

This makes use of the node.isExecuted built in variable, and a JS ternary operator, to decide whether to use the initial value or the value from the last iteration of the loop. Examine the expression in the Increment Loop Var node for details.

Key elements to making this work.

  • All of the expressions must reference specific Set nodes by name (e.g. $('').first().json.page). Nothing can just reference an attribute of the input (immediately previous node) (i.e. NOT $input.first().json.page and NOT $json.page).
  • The initial (first loop iteration) value must be set outside (previous to) the loop.
  • There must be a second Set node within the loop that forwards the value back to the Increment Set node, preferably using a different name (prevPage) at the beginning of the loop, because the Increment node can’t refer to itself in an expression.
  • The increment node’s expression must have the ternary conditional clause (i.e. (test) ? valueIfTrue : valueIfFalse) to choose whether to use the initial value, or increment the value (prevPage) forwarded from the other Set node within the loop.
5 Likes

Pre-emptive reply to myself… I realize this can also be done in Code nodes by referencing $getWorkflowStaticData but each Code node sets up a JS execution sandbox that can slow things down, so if they can be avoided, they probably should be.

1 Like

This is pure genius. The example is really well built and helped me understand the concept without resorting to ChatGPT. Thank you for sharing! :heart:

1 Like