A family thing



ServiceNow allows writing scripts mainly based on Javascript (ES5 till San Diego release). That means it builds on and depends on several Javascript concepts. Now, there are some concepts which if used incorrectly could result in surprising results. One we would look at briefly today is a concept called as scope.

There are two scopes within Javascript ES5, function scope and global scope. In very simplified terms, variables declared within a function are available to be used only within that function scope. If you write anything outside a function, that becomes available in the global scope and any script can access it and modify it.

In ServiceNow context, consider you are using glide record variables like current, previous or glide records with common names like gr, inc etc. And rather than using them within a function (encapsulated code) and forcing them to use the function scope, you use them outside a function i.e. in the global scope. You run a risk of inadvertently using a variable with same name but used and populated by some other script. It could result in some unexplainable behaviour and would make Don BR very unhappy.

Although, ServiceNow automatically populates a function wrapper when creating business rule and thus reducing issues with wrong scopes, you should be aware of the reasons behind it. Encapsulation should also be considered and practiced while writing background scripts, UI Actions and scheduled jobs. With Tokyo release and scoped app support for ES6, you can use let/const which do not create a global property/variable. However encapsulating the code is always a good practice.









Creative Commons License

Comments