Every once in a while, I look into the top search terms people have entered into Google or Bing (lol, who uses Bing?) that take them to this site. I do this to see if there are any common questions that people come here looking for answers to, but which I don’t yet have an article to answer. This month, that search term is “Can Script Includes use current”. This article aims to provide an answer to that question.
The question
I interpret the question “Can Script Includes use current” to mean:
If I write a function inside a Script Include (SI), and then call it from a Business Rule, can that function (in the SI) access the current object (from the Business Rule)?
Here’s an example SI which is attempting to do exactly that:
var CanIUseCurrent = Class.create(); CanIUseCurrent.prototype = { initialize: function() {}, tryUsingCurrent: function() { gs.info('The current record\'s display value is: .', current.getDisplayValue()); //^ This is bad! }, type: 'CanIUseCurrent' };
As you can see, the tryUsingCurrent() method is accessing a variable called current which is not declared or defined anywhere within the Script Include itself. Below, we’ll discuss whether this is possible, and whether it’s a good idea.
The short answer
The short answer to this question is: Yes, technically you can access anything that lives in the “calling” scope - but you shouldn’t. At least not without some extra steps to achieve “function purity”, which I’ll describe more in the long answer below.
If you take one thing from this article, let it be this:
Whenever possible, do not rely on “context” or the external/parent scope from which you expect your function to be called.
Never assume anything that you don’t have to, about any scope other than the function-scope you’re currently writing in.
There are exceptions to this rule, such as for truly-global objects like gs or the GlideRecord class. For the most part though, if it isn’t global, and it isn’t defined or passed into your script, don’t rely on it; or, more to the point: don’t assume that it exists!
The short solution
If you just want a quick answer without a lot of explanation, here it is:
The correct way to access the “current” object in a Script Include, is to pass it into the function you’re calling (and preferably, to use a variable name within the method other than “current”).
Note: Keep in mind that when handling objects in JavaScript, you’re passing by reference, not by value. This basically means that anything that you do to the object in the Script Include, will also happen to that object in the Business Rule - even if your SI method doesn’t return anything!
Since this is the “short” solution, I’ll spare you the explanation of pass-by-reference (PBR). If you want to know more about it - and you should - you can read more in my article on the subject, here.
The longer answer
Okay, so here’s where we’re going to get into some “philosophical” shit, but I promise not to go too far off the deep-end on you.
Let’s talk about function purity, and why it’s awesome.
What is a pure function?
A pure function is a function where the results of the function are not dependent on anything outside of the function itself, and what’s passed into it. A pure function also has no side-effects (it takes an input, returns an output, and doesn’t modify anything outside of its own scope).
For the most part, this means that what the function returns will be effectively identical as long as the exact same value is passed into it. Doesn’t matter what time of day it is, what scope it’s run in, or whether robots have risen up to finally overthrow humanity; the function will always return the exact same value, as long as the input parameters are exactly the same.
To put it another way, pure functions do not care about any external “state” or context.
Of course, truly pure functions are often not possible or ideal in ServiceNow, because a lot of the code we write is going to rely on what data is found in the database; and the database is definitely “external” to the function.
That said, you can imagine doing a query in one function, and passing that GlideRecord into another function. That second function would be able to be effectively pure, because as long as a GlideRecord corresponding to a record with the exact same values is passed into it, you can reasonably expect it to behave in the exact same way.
Note: This isn’t to say that a function should always do exactly the same thing every time it’s called; just that the only thing which should impact what the function does, should be what you’re passing into it (whenever possible).
Why are pure functions awesome?
Pure functions are much more readable and much more predictable in terms of what they’re going to actually do, given a specific input. This makes debugging, modifying your code’s functionality, and writing modular code much easier.
Pure functions are also often much more reusable, which is a desirable property of code. The DRY (Don’t Repeat Yourself) principle applies not only to blocks of code within a function, but to entire functions as well! By writing a function which doesn’t rely on state, you’ve written a function which can be reused from any context, to do the one specific job that it was designed to do.
As an example of this reusability, consider the CanIUseCurrent Script Include near the top of this article. - What if you wanted to call this function from a background script, or from another Script Include? You’d have to declare a variable in the calling scope called “current” and set it to a GlideRecord on the same table as the Business Rule from which the tryUsingCurrent() method was originally intended to be used.
And what if you wanted to call it from another Business Rule on another table? - You’d be forced to name some other variable “current”, which would collide with the existing “current” variable in that Business Rule. You can imagine how messy things could get!
Pure functions don’t have any of these problems.
How do I write a pure function?
Let’s have another look at the example Script Include from the top of this article:
var CanIUseCurrent = Class.create(); CanIUseCurrent.prototype = { initialize: function() {}, tryUsingCurrent: function() { gs.info('The current record\'s display value is: .', current.getDisplayValue()); //^ This is bad! }, type: 'CanIUseCurrent' };
In this script, you’ll see that on line 6, it’s calling current.getDisplayValue(). However, the current object is not defined anywhere in that function, and isn’t passed into it! So how could we rewrite this function so that it’s “pure”?
Easy! Rather than relying on the state/scope/context from which your code is called, simply have your code accept the relevant “state” as input parameters! Consider the following update to the CanIUseCurrent Script Include mentioned above. Note the changes to the tryUsingCurrent() method, on lines 5 and 6:
var CanIUseCurrent = Class.create(); CanIUseCurrent.prototype = { initialize: function() {}, tryUsingCurrent: function(grIncident) { gs.info('The current record\'s display value is: .', grIncident.getDisplayValue()); }, type: 'CanIUseCurrent' };
With the old version of this SI, we’d have to call the function from a Business Rule with the “current” object containing a record that the script expects to be there. That call would look something like:
(function executeRule(current, previous /*null when async*/) { new CanIUseCurrent().tryUsingCurrent(); })(current, previous);
Note that I haven’t passed anything into the function being called, so it’s entirely reliant on the state of the Business Rule from which I’ve called it.
However, with the new version of the Script Include above (where the tryUsingCurrent() method accepts an argument that it calls grIncident), the function becomes “pure” and can be called in pretty much the same way, with only a minor tweak - passing in current as an argument to the function (now that it accepts an argument) like so:
(function executeRule(current, previous /*null when async*/) { new CanIUseCurrent().tryUsingCurrent(current); })(current, previous);
So there you have it! Aim for purity whenever you can by passing any necessary context into your function, and try to avoid your code relying on any external-state assumptions. 👍
- March 2024
-
February 2024
- Feb 12, 2024 5 Lessons About Programming From Richard Feynman
- July 2023
- May 2023
- April 2023
-
December 2022
- Dec 13, 2022 ServiceNow Developers: BE THE GUIDE!
- October 2022
-
August 2022
- Aug 23, 2022 Using .addJoinQuery() & How to Query Records with Attachments in ServiceNow
- Aug 18, 2022 Free, Simple URL Shortener for ServiceNow Nerds (snc.guru)
- Aug 16, 2022 How to Get and Parse ServiceNow Journal Entries as Strings/HTML
- Aug 14, 2022 New tool: Get Latest Version of ServiceNow Docs Page
- March 2022
- February 2022
- May 2021
- April 2021
- February 2021
-
November 2020
- Nov 17, 2020 SN Guys is now part of Jahnel Group!
- September 2020
- July 2020
-
January 2020
- Jan 20, 2020 Getting Help from the ServiceNow Community
- December 2019
- November 2019
-
April 2019
- Apr 21, 2019 Understanding Attachments in ServiceNow
- Apr 10, 2019 Using Custom Search Engines in Chrome to Quickly Navigate ServiceNow
- Apr 4, 2019 Set Catalog Variables from URL Params (Free tool)
- Apr 1, 2019 Outlook for Android Breaks Email Approvals (+Solution)
- March 2019
-
February 2019
- Feb 27, 2019 Making Update Sets Smarter - Free Tool
-
November 2018
- Nov 29, 2018 How to Learn ServiceNow
- Nov 6, 2018 ServiceNow & ITSM as a Career?
- October 2018
- September 2018
-
July 2018
- Jul 23, 2018 Admin Duty Separation with a Single Account
-
June 2018
- Jun 19, 2018 Improving Performance on Older Instances with Table Rotation
- Jun 4, 2018 New Free Tool: Login Link Generator
-
May 2018
- May 29, 2018 Learning ServiceNow: Second Edition!
- April 2018
- March 2018
-
February 2018
- Feb 11, 2018 We have a new book!
- November 2017
-
September 2017
- Sep 12, 2017 Handling TimeZones in ServiceNow (TimeZoneUtil)
- July 2017
-
June 2017
- Jun 25, 2017 What's New in ServiceNow: Jakarta (Pt. 1)
- Jun 4, 2017 Powerful Scripted Text Search in ServiceNow
- May 2017
- April 2017
-
March 2017
- Mar 12, 2017 reCAPTCHA in ServiceNow CMS/Service Portal
-
December 2016
- Dec 20, 2016 Pro Tip: Use updateMultiple() for Maximum Efficiency!
- Dec 2, 2016 We're Writing a Book!
-
November 2016
- Nov 10, 2016 Chrome Extension: Load in ServiceNow Frame
- September 2016
-
July 2016
- Jul 17, 2016 Granting Temporary Roles/Groups in ServiceNow
- Jul 15, 2016 Scripted REST APIs & Retrieving RITM Variables via SRAPI
-
May 2016
- May 17, 2016 What's New in Helsinki?
-
April 2016
- Apr 27, 2016 Customizing UI16 Through CSS and System Properties
- Apr 5, 2016 ServiceNow Versions: Express Vs. Enterprise
-
March 2016
- Mar 28, 2016 Update Set Collision Avoidance Tool: V2
- Mar 18, 2016 ServiceNow: What's New in Geneva & UI16 (Pt. 2)
-
February 2016
- Feb 22, 2016 Reference Field Auto-Complete Attributes
- Feb 6, 2016 GlideRecord & GlideAjax: Client-Side Vs. Server-Side
- Feb 1, 2016 Make Your Log Entries Easier to Find
-
January 2016
- Jan 29, 2016 A Better, One-Click Approval
- Jan 25, 2016 Quickly Move Changes Between Update Sets
- Jan 20, 2016 Customize the Reference Icon Pop-up
- Jan 7, 2016 ServiceNow: Geneva & UI16 - What's new
- Jan 4, 2016 Detect/Prevent Update Set Conflicts Before They Happen
-
December 2015
- Dec 28, 2015 SN101: Boolean logic and ServiceNow's Condition Builder
- Dec 17, 2015 Locate any record in any table, by sys_id in ServiceNow
- Dec 16, 2015 Detecting Duplicate Records with GlideAggregate
- Dec 11, 2015 Array.indexOf() not working in ServiceNow - Solution!
- Dec 2, 2015 Understanding Dynamic Filters & Checking a Record Against a Filter Using GlideFilter
- October 2015
-
August 2015
- Aug 27, 2015 Easily Clone One User's Access to Another User