Let's dive into limited looping options of the SSJS.
FOR available in AMPScript.
for loop might be a bit long to write, but it has a lot of excellent properties:
- Works with
continuestatements for better looping control.
- Both initial and increment expressions can do multiple things (examples available below).
- Condition is not limited to iterable length (although it is the most popular way).
- Fast across various scenarios.
Let's break the script down to five steps each
for loop follows:
- Execute initial expression (
var i = 0in the above example).
- Evaluate the condition (
i < array.length). If it is false - the loop terminates. If true:
- The statement within the loop is executed (
- Finally, the increment expression will evaluate (
- The loop goes back to step 2 until it is false.
To optimize speed, cache the length used for condition. By assigning it to a variable in initial expression, the loop won't have to calculate the length on each iteration.
You can get more logic within the
for declaration to, for example, have a cleaner statement within the loop:
As ES6 for...of loop is not available in SSJS, you will use this one in most scenarios.
In SSJS however, the ES6 for...of loop is not available.
Object.entries() also does not exist. This makes the
for...in the only solution for iterating over objects.
In simple scripts created in SSJS you shouldn't have issues with the prototype methods and properties, however, if you encounter any issues (or want to code defensively), use
Remember to use
for...in only for looping over objects. For any other scenario classic
for loop is both safer and more powerful.
You Should Know
If you ever use
for...in loop for an array, remember that the loop-counter variable will return a string instead of a number. For example
'0' for first array item instead of
while loop executes its statement as long as the condition evaluates to true.
To break out of
while loop, there must be logic within it that will change the condition to false (or a
while loop is the best option for iterating over big arrays.
while, but the code runs once before evaluating the condition.
Perfect when you need to run an API call, check whether there are more pages of outcomes and act accordingly.
You Should Know
As you can see, in the first line we added a label for the first
for loop. Then, in the statement within the second
for loop, we used
break followed by the label. Once executed, it will break both for loops, even if there were still iterations in the main one. The same approach works with the