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:33 AM
As you have declared the variable in the first function so its scope is limited to that. Now if you want that variable to be available to the second function, pass it as a parameter to second. See below example.
(function executeRule(current, previous /*null when async*/) {
var ci = '';
var diagLogs = [];
diagLogs.push('test!'); // This works
getAssignmentCI(diagLogs);
gs.log(diagLogs.join(',')); // This does not print after attempting to add on to array in function
}
function getAssignmentCI(diagLogs) {
diagLogs.push('Pass 1 started');
}
Another way is to make it global by declaring it outside all the functions but global variables are not recommended can cause conflicts.
Hope that helps!
Muhammad
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎09-20-2020 08:00 AM
Hope you are doing good.
Let me know if I have answered your question.
If so, please mark appropriate answer as correct & helpful to close the thread.
If not, please let us know if you need some more assistance.
Regards
Ankur
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader