unlocking the power of servicenow scripting: pro developer insights
ServiceNow scripting isn’t rocket science – even a developer with a few months of experience can get up to speed if they’re willing to put in the work. But here’s the secret sauce to becoming a top-tier developer: writing code that’s not just efficient and reliable, but also smartly error-handled to avoid those “oops” moments.
Want to truly stand out? It’s all about mastering the powerful APIs, methods, and knowing exactly when and how to use them. Because let’s be real, knowing what to use is half the battle – knowing when and how to use it? That’s where the magic happens.
The Hidden Gem: The "getRefRecord" Method
In the world of ServiceNow development, there are several methods that often go unnoticed, despite their tremendous potential. One such method that deserves more attention is the "getRefRecord" method.
var grIncident = new GlideRecord("incident");
grIncident.addQuery("priority", 1); // Query for priority 1 incidents
grIncident.query();
while (grIncident.next()) {
var grProblem = grIncident.problem.getRefRecord(); // Retrieve the related problem record
if (grProblem.isValidRecord()) { // Ensure the problem record is valid
grProblem.notes = "This problem is associated with a Priority 1 incident"; // Update the work notes
grProblem.update(); // Save the changes
}
}
GlideRecord get Method: A Key to Efficient Data Retrieval
var grIncident = new GlideRecord('incident');
if(grIncident.get('99ebb4156fa831005be8883e6b3ee4b9')) //this method returns true when found matching record
gs.info(grIncident.number);
var grIncident = new GlideRecord('incident');
if(grIncident.get('number',"INCXXXXX")) //this method returns true when found matching record
gs.info(grIncident.short_description);
Note: Remember to always use this method with if condition, using method without if condition and updating record could create new entry in related table if record not found with given filter.
Unlocking the Full Potential of the g_scratchpad Object
Display BR:
(function executeRule(current, previous /*null when async*/) {
// Access a field that is not part of the form (Assigned Group in this case)
var assignedGroup = current.assignment_group.getDisplayValue(); // This field is not on the form
g_scratchpad.assigned_group = assignedGroup; // Store it in g_scratchpad
})(current, previous);
On Load Client Script:
function onLoad() {
// Access the assigned group value from g_scratchpad
if (g_scratchpad.assigned_group) {
// Display the assigned group value
alert('The Assigned Group is: ' + g_scratchpad.assigned_group);
// Optionally, display it as an info message on the form
g_form.addInfoMessage('The Assigned Group is: ' + g_scratchpad.assigned_group);
}
}
Best Practices for Null Value Verification
if (firstName == "") gs.addInfoMessage("Please enter first name");Sure, it works... most of the time. But here's the kicker: it doesn't always do the job. Why? Because in the ever-wild world of programming, "empty" doesn’t just mean one thing. It could be `null`, `undefined`, or the classic empty string (`""`). If you’re only checking one of these, you’re leaving your code vulnerable to bugs like a leaky bucket.
1. JSUtil API:
If you’re doing server-side scripting in ServiceNow, JSUtil is your secret weapon. This handy object has a couple of methods that will save you from those embarrassing moments where your code doesn’t catch an empty value. So, let’s get into it.i) JSUtil.nil(object) method: This method is a real game-changer. It checks if an object is `null`, `undefined`, or an empty string—all in one neat little package. No need to guess or perform multiple checks. Just use `JSUtil.nil()` and breathe easy.
Example:
var firstName = "ServiceNow";
var lastName = "";
if (JSUtil.nil(firstName))
gs.print("First Name is empty");
else
gs.print("First Name is not empty");
if (JSUtil.nil(lastName))
gs.print("Last Name is empty");
else
gs.print("Last Name is not empty");
Output:
First Name is not empty
Last Name is empty
Pretty straightforward, right? JSUtil.nil() covers all the bases, so you don’t have to worry about leaving any potential empty value unchecked.
var firstName = "ServiceNow";
var lastName = "";
if (JSUtil.notNil(firstName))
gs.print("First Name is " + firstName);
else
gs.print("First Name is empty");
if (JSUtil.notNil(lastName))
gs.print("Last Name is " + lastName);
else
gs.print("Last Name is empty");
Output:
First Name is ServiceNow
Last Name is empty
2. gs.nil() Method
Guess what? You don’t have to stop with JSUtil. gs.nil() is another nifty method that can handle null checks. It’s perfect when you're working with GlideRecord objects, but it also works on normal dot-walked variables.Example with GlideRecord:
var grUser = new GlideRecord('sys_user');
if (grUser.get("XXXXX")) {
if (gs.nil(grUser.first_name)) {
gs.addInfoMessage("First name is missing!");
}
}
Or, if you’re just checking a regular GlideRecord object:var gr = new GlideRecord("sys_user");
gs.info(gs.nil(gr)); // This will check if the GlideRecord object itself is null or empty
3. current.name.nil()
Working with records and need a quick check? You can even use nil() directly on fields within the glideobject record.Example:
if (current.name.nil()) { gs.addInfoMessage("Name field is empty"); }
4. The Simple `if (name)` Check
Finally, for client-side scripts, you can simplify things even further with a good old-fashioned `if (name)` check. This check will cover all three empty states: empty string, `undefined`, and `null`. It’s the all-in-one solution.Example:
if (!name) { gs.addInfoMessage("Name is either empty, undefined, or null"); }
Powerful Error Handling: Using try-catch in Conjunction with gs.error
What Exactly is a Try-Catch Block?
Here’s the basic syntax:
try {
// Code that might cause an error
} catch (error) {
// Code that handles the error
gs.error("An error occurred in script inlcude XXXXX: " + error.message);
}
Why You Should Always Use Try-Catch in Scripting
2. Improve Debugging and Troubleshooting
3. Enhance User Experience
Comments
🚀 Power Up Your ServiceNow Career
Join a growing community of smart ServiceNow professionals to stay ahead in interviews, sharpen your development skills, and accelerate your career.