Variable created outside of function not working within one

aaron_anderson
Tera Expert

I have a business rule that needs to share a variable with 5 other functions within the script.

In the example below, I am trying to use diagLogs globally to store lots of diagnostic information. Inside the getassignmentCI function, the script doesn't add the new value to diagLogs and the script actually stops working. If I comment out the new function altogether and just push "test!" it works.

How can I make this public for all the functions in the business rule?

(function executeRule(current, previous /*null when async*/) {
   var ci = '';
   var diagLogs = [];
   diagLogs.push('test!'); // This works

   getAssignmentCI();
   gs.log(diagLogs.join(',')); // This does not print after attempting to add on to array in function
}

function getAssignmentCI(ci) {
   diagLogs.push('Pass 1 started');
}

6 REPLIES 6

BryanS413339635
Tera Guru

Wouldn't you need to declare the variable outside of the first function so it's global?

Moving var diagLogs = []; to the first line (outside of the function execute) section didn't change the outcome. It does get the first push but it doesn't recognize the second one within the lower function.

Ankur Bawiskar
Tera Patron
Tera Patron

Hi,

you are not passing the array to that function as parameter; hence it won't be recognised

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Ankur Bawiskar
Tera Patron
Tera Patron

Hi,

As best practice you should not use global variables in business rules

User-defined variables are globally scoped by default. If a new variable is declared in an order 100 business rule, the business rule that runs next at order 200 also has access to the variable. This may introduce unexpected behavior.

To prevent such unexpected behavior, always wrap your code in a function. This protects your variables from conflicting with system variables or global variables in other business rules that are not wrapped in a function. Additionally, variables such as current must be available when a function is invoked in order to be used.

Global variables in business rules

Business rules best practices

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader