Variable created outside of function not working within one
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎09-17-2020 08:00 AM
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');
}
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎09-17-2020 08:09 AM
Wouldn't you need to declare the variable outside of the first function so it's global?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎09-17-2020 08:19 AM
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.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎09-17-2020 08:11 AM
Hi,
you are not passing the array to that function as parameter; hence it won't be recognised
Regards
Ankur
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎09-17-2020 08:12 AM
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
Regards
Ankur
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader