Basics

SuiteScript Loops

Loop Structures

SuiteScript loops use for and while with governance limits in NetSuite.

Introduction to SuiteScript Loops

Loops in SuiteScript are fundamental constructs that allow you to execute a block of code repeatedly. They are particularly useful in scenarios where operations need repeating, such as processing each item in a list, iterating over search results, or applying a function to each element in an array. SuiteScript supports for and while loops, offering flexibility in how you iterate over data.

Using the For Loop

The for loop in SuiteScript is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. It is comprised of three expressions: initialization, condition, and final expression. The loop continues until the condition evaluates to false.

In this example, the loop starts with i initialized to 0 and continues until i is less than 10. The log.debug function logs each iteration's current index.

Implementing the While Loop

The while loop in SuiteScript executes a block of code as long as a specified condition is true. This loop is useful when the number of iterations is not known beforehand, and you want to iterate until a specific condition changes.

In this example, the while loop continues until count is no longer less than 5. Each iteration increments count by one and logs the current count.

Handling Governance Limits

NetSuite imposes governance limits on SuiteScripts to ensure optimal performance and resource utilization. When using loops, it's crucial to manage these limits, particularly in long-running scripts. Use nlapiYieldScript function to yield the script execution when approaching governance limits, allowing NetSuite to manage system resources efficiently.

In this example, the nlapiYieldScript is called every 100 iterations to yield control back to NetSuite. This practice helps in managing governance units and avoiding script termination due to exceeding limits.

Previous
Switch