Blog Summary

  • ServiceNow scripting interview questions help students and professionals understand the core concepts of different tools.
  • The interview questions on client-side scripting in ServiceNow are focused on the architectural designs and practical scenarios.
  • ServiceNow interview questions on scripting cover different topics like GlideAjax, UI, client-side and server-side scripts, business rules, security, and access control lists.

Scripting in ServiceNow is where you transform your theoretical understanding into practical use. The major focus remains on concepts like Business rules, Client scripts, Server scripts, Security, integrations, and automations. 

Interviewers ask questions around these concepts to understand your hands-on skills with the platform. To help you prepare better, we have created a guide with around 25 common questions that you might come across during an interview. These interview questions on scripting are divided into six sections, focusing on different areas. 

ServiceNow Scripting Concepts Interview Questions

The section focuses on the fundamentals servicenow client script interview questions. It includes common topics like business rules, Glide Ajax, scripting, and GlideRecord. 

1. What is a Business Rule, and what are the different types based on when they run?

Ans. A business rule is a part of Server-side JavaScript that is executed when a record table is displayed, updated, inserted, or deleted. They are the backbone of server-side automations in ServiceNow. They are divided into four types, based on when they are used:

  1. Before: It runs before the record is written in the database. It is used to modify field values before you save or verify the data. 
  2. After: It runs immediately after the record has been updated in the database. It is used when you need to act on other related records. 
  3. Async: It is similar to the After rule, but does not run in the same transaction. It is scheduled and executed by the scheduler afterwards. 
  4. Display: It runs on the servers, but the browsers render the form. Its use is to run GlideRecord queries or gs logics. 

2. What is the key difference between a Client Script and a Business Rule?

Ans. Client scripts are executed on the client browser. It includes onload, onsubmit, onchange, and oncellEdit options. It helps change form appearance and make fields mandatory or share alerts based on user actions. 

However, a business rule in servicenow is a server-side scripting method used to perform server operations when a record is inserted, updated, deleted, or queried. It has four types, including after, before, async, and display. 

3. What is a Script Include, and when should it be used?

Ans. Script Include in ServiceNow is a reusable part of server-side JavaScript. It is like a personal toolbox that lets you logically save similar code and use it anywhere you need. It is a custom class that allows business rules, workflows, or other script includes to use the code you have stored. 

A script include should be used: 

  • In other script includes, it is used to share and extend logic. 
  • In business rules for server-side automations. 
  • In the workflow activity for overall backend processes. 
  • On client script using GlideAjax for server calls form client side code. 

4. What is the difference between the four Client Script types in terms of the isLoading parameter?

Ans. The standard client scripts handle the isLoading parameter based on how and when the script executes. The difference between the four client scripts is: 

  • onChange is the only script where isLoading actively works. It is used to avoid unnecessary code executions. 
  • In the onLoad Client Script, technically there is no isLoading parameter present, but it claims that in onLoad, the isLoading parameter is always true.
  • onSubmit and onCellEdit scripts do not use or receive the isLoading parameter. 

5. What is GlideRecord, and what are its most commonly used methods?

Ans. GlideRecord in ServiceNow is one of the core server-side components that interact with table data. It is a part of a platform over SQL that allows scripts to build, filter, and execute database queries. The most commonly used methods are: 

  • Query Building: addQuery (field, operator, value) is used to create conditional queries for the table data. 
  • Executing: query() runs the build query against the database and returns a data set to be iterated. 
  • Iterating: next() moves to the next record in the result set. It returns false once there are no more records and is mostly used inside a while loop.
  • Single-record lookup: get(sys_id) or get(field, value) is a shortcut. It queries and positions the GlideRecord on the first matching record in one call, returning true/false.

6. What is the difference between get() and query() on a GlideRecord?

Ans. The core difference between get() and query() is that get() retrieves a single specific record and moves the cursor to it, and query() is used to execute a search to return a dataset of records that must be iterated.

Feature get() query()
Primary Purpose Retrieves one record. Retrieves a collection of records.
Inputs Accepts sys_id, field, and value. Relies only on the addQuery() filter.
Cursor Position Loads record data into objects automatically. Uses next() to load data, and the cursor stays before the first record.
Return Value Returns true if found or false if not. Returns void (nothing).

7. What is GlideAjax, and how does client-server communication work with it?

Ans. GlideAjax in ServiceNow is used to model the client-side code to server-side code. It allows users to call server code from the browser, get results, and update the interface. 

The client-server communication happens when:

GlideAjax initiates a new object that passes the server-side script that it wants to contact. 

  • Using the addParam() method, the script sends data variables to the server. 
  • Sysparm_name is compulsory to specify which function is to be pointed to in the Script Include. 
  • Lastly, use getXML() to make asynchronous calls to trigger the callback function. 
  • In the callback function, the returned value is used to update the form. 

8. What is the purpose of the setWorkflow() method on GlideRecord?

Ans. The setWorkflow() method in GlideRecord approves or disapproves the execution of workflows, business rules, and auditing/script engines during database functions. 

It is mainly used on bulk data loads, migrations, or cleanup scripts where hundreds of records are changed. Still, there are no hundreds of notification emails, recalculations, or downstream Business rules. 

Remember that setWorkflow () suppresses the business rule, which can also suppress the validations. So ensure that they are used in scripts run by administrators, not in everyday automations.

ServiceNow Scripting Basics Interview Questions

Let us dive deeper into the server-side Scripting Concepts in ServiceNow. 

9. What is the difference between GlideRecord and GlideAggregate?

Ans. The major difference between GlideRecord and GlideAggregate is that: 

Aspects GlideRecord GlideAggregate
Purpose Get actual record data row by row. Calculate aggregate values using COUNT, SUM, AVG, MIN, MAX.
Data Returned Full field values for each matching record. Single calculates values per group, not individual records.
Performance Slow for large datasets as you have to loop and calculate manually. It is faster as the calculations happen at the database level.
Grouping No built-in grouping. Supports groupBy(field)for per-group aggregates.
Usage For reading and editing records. In dashboards, counts, reports, and SLA metrics.

10. What is the difference between addQuery() and addEncodedQuery() in GlideRecord?

Ans. The major difference between addQuery() and addEncodedQuery() is based on structure, readability, and risks. 

  • addQuery(field, operator, value): It adds one condition at a time using clear parameters. It is safe and maintainable for building queries in a script. 
  • addEncodedQuery(encodedQueryString): It accepts the entire query string in ServiceNow’s internal encoded query syntax. 
Aspects addQuery() addEncodedQuery()
Readability Clear, parameterized Compact, harder to read for complex logic
Used for Dynamic/user-supplied values Static, developer-authored filters (e.g., copied from a list URL)
Risks Low, as values are passed as parameters Higher, as it joins raw input, risks query injection
Used with addOrCondition() for OR logic Can embed AND/OR directly in the string (^, ^OR)

11. What is the difference between setValue() and setDisplayValue() in GlideRecord?

Ans. setValue() and setDisplayValue() are used to write a value into a field. The major differences are: 

Aspect setValue() setDisplayValue()
What it sets The raw, underlying stored value. The human-readable display value.
Reference fields Requires the sys_id. Looks up a record by the display field and stores its sys_id.
Risk None, if the sys_id is correct. Can resolve to the wrong record if display values aren’t unique.
Performance Faster as no lookup is needed. Slightly slower as it performs an internal lookup.
When to use When you already have the sys_id. When you only have a name/label (e.g., imported data).

12. What is a Script Action, and how is it different from a Script Include?

Ans. Script Actions are event-driven server-side scripts that run in the background whenever a specific event occurs. It is attached to a specific event in the Event Queue. It is different from script include in different ways: 

Aspect Script Action Script Include
Trigger Runs when an event is raised. Event (gs.eventQueue()) It is called by other code.
Execution Asynchronous and uses the scheduler but has a slight delay. Synchronous and runs immediately.
Use case Decoupled and non-blocking work. (e.g., send an alert) Reusable logic that is to be answered right away.
Reusability Tied to a specific event. Get called from Business Rules, UI Actions, GlideAjax, etc.

13. What is the difference between getXML(), getXMLAnswer(), and getXMLWait() in GlideAjax, and what’s the drawback of getXMLWait()?

Ans. All three methods respond to underlying calls to a Client Callable Script Include. However, they differ in the way they provide results. 

Method What it returns Drawback
getXML(callback) It responds with a full raw XML response object into the callback function. It has to be manually parsed.
getXMLAnswer(callback) The ‘answer’ value is automatically extracted and passed to the callback as a simple string. None, as it is a default method to be used.
getXMLWait() The values are returned directly without a callback. It blocks/freezes the browser UI thread and is unsupported in UI16/Next Experience.

Note: getXML(callback) and getXMLAnswer(callback) are asynchronous versions. 

getXMLWait() is a synchronous version. 

ServiceNow Client-Side Scripting & UI Interview Questions

This section focuses on the interview questions on client-side scripting in servicenow along with the UI. 

14. What is the key difference between a UI Policy and a Client Script?

Ans. Client Scripts are used for the clients and run on the browser. Users who know JavaScript can define scripts to run in the client browser. 

The UI policies offer alternatives to the client scripts for changing information on the form. Users with Personalize rules and UI policy administrators can use UI policies. 

Aspect UI Policy Client Script
Configuration These are declarative and have no-code. It requires JavaScript to run.
Capabilities This makes fields mandatory/ read-only /visible toggles based on a condition. It has full control of alerts, calculations, GlideAjax calls, and any logic.
Server-side enforcement It is possible, if paired with a Data Policy. It cannot happen unless a Business Rule/Data Policy separately backs the script.
Best for Basic, simple field-state changes. Complex or custom form behavior.

15. What is the difference between a UI Policy and a Data Policy?

Ans. Both UI policies and data policies usually provide very similar outcomes but are used at different layers of the platform. 

UI Policies: 

  • They are based on Client scripts for a specific form /view.
  • It can be bypassed using REST API, import sets, scripts, and flow designer
  • It is used to define the on-screen experience for forms. 

Data Policies: 

  • They are based on server scripts at the table level. 
  • They can’t be bypassed and are applied irrespective of the entry point. 
  • Ensures that a business rule is always true and is not violated. 

16. Why don’t you use the initialize() function in a Script Include that will be called via GlideAjax?

Ans. In ServiceNow, the initialize() function should not be used as it overrides the base class AbstractAjaxProcessor.initialize() methods. Overriding eventually breaks the process of GlideAjax parameters and the generation of XML responses. Let us understand this in detail: 

  • The script included for GlideAjax extends AbstractAjaxProcessor. The base class has its own initialize() function, which handles the parsing of sysparm_name and the other parameters. 
  • It should not be overridden, as defining your own initialize() function in the script includes’ object would replace the parent version rather than extend it. 
  • If you need to set up a client-callable Script Include, use a different function and call it at the start of the public function that needs it rather than naming it initialize(). 

17. How do you restrict who can edit a field, purely from the client side, and why is that not fully secure?

Ans. Client-side roles are useful for creating an effective user experience, but they are not secure enough. To restrict who can edit a field: 

  • Use onLoad Client Script with g_user.hasRoleExactly() and g_form.setReadOnly() for users who should not be able to edit it. 
  • It is not secure, as client scripts execute when a specific form is rendered from the browser. If anyone has access to the API, script, or import sets, they can change the fields, bypassing the form. 
function onLoad() {
    if (!g_user.hasRoleExactly('admin') &&
        !g_user.hasRoleExactly('incident_manager')) {

        g_form.setReadOnly('assignment_group', true);
        g_form.setReadOnly('assigned_to', true);
    }
}

ServiceNow Security and Access Control Interview Questions

Security and access are important components in ServiceNow scripts. One wrong access can bypass all security measures and become risky for your organization. 

18. How does ServiceNow evaluate Access Control Lists (ACLs)?

Ans. In specific ACL rules, the conditions are passed simultaneously, and they are evaluated in order of precedence. 

  • Roles are evaluated faster, and if the user has one of the roles, then the condition is passed.  
  • Conditions are evaluated next. They are standard condition creators that must evaluate to true. 
  • Lastly, the script is evaluated as it is more resource intensive. The server-side script must return true or set an answer variable to true. 

19. What is the special “answer” variable used for in an ACL script?

Ans. In a ServiceNow ACL script, the special “answer” variable is used to specifically give or deny access to a record or a field. The script assigns a Boolean value to this variable: 

  • If the answer is true, access is granted. 
  • If the answer is false, access is denied. 

If the script does not set a specific answer, the ACL behaviour can be inconsistent. So each ACL script should ensure that every code has a path that ends with a proper answer, as mentioned above. 

20. How would you secure a custom field so that only admins can ever edit it, no matter how the record is updated?

Ans. To secure a custom field, ACL scripts are used:

Step 1: Go to System Security in Access Control and create a new ACL scoped to the specific table and fields. 

Step 2: In the required role field, add the admin role. 

Step 3: Keep the Condition/Script field blank if the role added is enough. Add a script if the rule is required to be more specific. 

ACL is the right way because they are evaluated by the platform for whether the data is edited via REST API integration, import set, background script, or flow designer. No code can bypass ACL scripts. 

21. What should you always include when calling an external REST API from a script (e.g., using RESTMessageV2)?

Ans. When calling an external REST API from a script, tools like RESTMessageV2 should be included. It helps: 

  • Error Handling: Network fails, timeouts, or false requests can lead to exceptions. Without try/catch, a handled error can break the entire business rule, not just the integration. 
  • Response Validation: The response body is not always valid JSON. Wrap JSON.parse() in its own try/catch. The error page will itself identify the uncaught exception during parsing. 
  • Timeout Limits: RESTMessageV2 allows you to call setHttpTimeout() without any specific timeout. External systems can tie up the calling transaction for longer than accepted. 
  • Log Management: Use gs.error() for failures, including the endpoint called, status code, and response.getErrorMessage() or the response body. With this, the responses are visible and identified in the system log. 
try {
    var r = new sn_ws.RESTMessageV2('My REST Message', 'get');
    r.setHttpTimeout(10000);
    var response = r.execute();
    var status = response.getStatusCode();

    if (status == 200) {
        var data = JSON.parse(response.getBody());
    } else {
        gs.error('External API call failed with status ' + status + ': ' + response.getErrorMessage());
    }
} catch (ex) {
    gs.error('Exception calling external API: ' + ex.getMessage());
}

ServiceNow Scenario-Based Scripting Interview Questions

The ServiceNow scenario-based questions focus on your understanding of applying your knowledge in real-time problems. 

22. An Incident should not be allowed to move to ‘Resolved’ or ‘Closed’ while related Incident Tasks are still open. How would you implement this?

Ans. I would use a before business rule on the incident that queries incident_task for open children and aborts the ones that are found. 

Before this, the business rule must be configured to run only when the state is changed to resolved or closed, so the check does not run on every unrelated field. 

The incident_tasks table queries the child tasks of the particular incident that are in open state, using addEncodedQuery() with an IN clause. The current.setAbortAction(true) is used to stop the save. 

The code: 

(function executeRule(current, previous) {
    var task = new GlideRecord('incident_task');
    task.addEncodedQuery('parent=' + current.sys_id + '^stateIN-5,1,2');
    task.query();

    if (task.next()) {
        gs.addErrorMessage('You cannot resolve this incident while related tasks are still open.');
        current.setAbortAction(true);
    }
})(current, previous);

23. When ‘Assigned to’ is filled in, the ‘Assignment group’ dropdown should only show groups that the user actually belongs to. How would you implement this?

Ans. I would use a scripted Reference qualifier on the assignment group. The steps involved: 

Step 1: Create a Client Callable Script Include with a function that accepts sys_id, queries the sys_user_grmember table for the user, and returns the matching sys_id group. 

Step 2: In the assignment group field dictionary definition, add a reference qualifier type to Script and point it at a call in your Script Include. 

In this case can just be handled where assigned_to is empty, so the assignment group field does not break or show every group by default. 

// Script Include
var BackfillAssignmentGroups = Class.create();
BackfillAssignmentGroups.prototype = Object.extendsObject(AbstractAjaxProcessor, {
    BackfillAssignmentGroup: function(userSysId) {
        if (!userSysId) return 'sys_id=';

        var groupIds = [];
        var grp = new GlideRecord('sys_user_grmember');
        grp.addQuery('user', userSysId);
        grp.query();

        while (grp.next()) {
            groupIds.push(grp.getValue('group'));
        }

        return groupIds.length ? 'sys_idIN' + groupIds.join(',') : 'sys_id=';
    },

    type: 'BackfillAssignmentGroups'
});

// Reference qualifier (on the dictionary entry for assignment_group):
// javascript: new BackfillAssignmentGroups().BackfillAssignmentGroup(current.assigned_to)

24. When a reference field (e.g., a custom ‘Requested For’ user field) changes, auto-populate the user’s email and user ID on the form. How would you build this end-to-end?

Ans. To build this, end to end, I will follow the given steps: 

  1. Client Script (onChange on the reference field): Protect against isLoading and an empty newValue first, then create a GlideAjax call, passing the new selected sys_id as a parameter. 
  2. Script Include (Client Callable): Read the passed sys_id with this.getParameter() and use gr.get(id) to find the sys_user record and return important fields. These are bundled together as a JSON string to pass back a single string value. 
  3. Callback: In the getXMLAnswer() callback, JSON.parse() the return string uses g_form.setValue() to populate target fields from the parsed object. 

Finally, I would focus on finding a user by returning an empty/default object. It ensures that the callback does not push when trying to read non-existent properties. 

// Client Script (onChange)
function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue === "") return;

    var ga = new GlideAjax('UserDetailsAjax');
    ga.addParam('sysparm_name', 'getUserDetails');
    ga.addParam('sysparm_userID', newValue);

    ga.getXMLAnswer(function(answer) {
        var data = JSON.parse(answer);
        g_form.setValue('u_user_email', data.email);
        g_form.setValue('u_user_id', data.user_name);
    });
}

// Script Include
var UserDetailsAjax = Class.create();
UserDetailsAjax.prototype = Object.extendsObject(AbstractAjaxProcessor, {
    getUserDetails: function() {
        var id = this.getParameter('sysparm_userID');
        var obj = { user_name: "", email: "" };

        var gr = new GlideRecord('sys_user');
        if (gr.get(id)) {
            obj.user_name = gr.getValue('user_name');
            obj.email = gr.getValue('email');
        }

        return JSON.stringify(obj);
    },

    type: 'UserDetailsAjax'
});

25. You need a checkbox ‘Is a problem required?’ that, when checked and the Incident is resolved, auto-creates a Problem record and links it back via a ‘Problem’ field. How?

Ans. In the incident table, use a Before business rule so that current.problem_id can be set and saved as part of this same update, without needing a second database round trip.

  • Condition: u_is_problem_required is true, AND state changes to Resolved – both conditions combined so this only fires exactly once, at the moment of resolution, for incidents actually flagged as needing a problem record.
  • Script logic: Create a new GlideRecord on the problem table, call initialize() to set it up as a new in-memory record, populate relevant fields, call insert() to save it and capture the returned sys_id, then set current.problem_id to that sys_id so the Incident record itself stores the relationship.
(function executeRule(current, previous) {
    var gr = new GlideRecord('problem');
    gr.initialize();
    gr.short_description = current.short_description;
    gr.description = current.description;

    var probId = gr.insert();
    current.problem_id = probId;
})(current, previous);
ServiceNow training CTA

Conclusion

By highlighting these ServiceNow Scripting interview questions, we have tried to help curate a guide for the students and professionals who are starting their career in ServiceNow. These questions not only test your platform understanding but also the practical knowledge that is required for any job profile. 

If you are also preparing for your ServiceNow interview but still get confused about how to grab your ideal role, then it is important to identify the correct ServiceNow career path. If not, you can simply connect to S2 Labs and get free consultancy on what your ServiceNow career choice should be.

Author

Shrey Sharma

Shrey Sharma is the Founder of S2 Labs and a 2019 Salesforce MVP. He's trained 50,000+ students into Salesforce careers and runs Salesforce Hulk, the largest Salesforce-focused YouTube community. He's been a featured speaker at Salesforce community events worldwide, and his mission with S2 Labs remains simple: real mentorship, hands-on projects, and a clear path from classroom to career.

Shrey Sharma

Latest Salesforce Insights