Purpose: How to execute code conditionally if a matching record exists or is found in ServiceNow using a Functional Programming style

Use: Use this script in a Server Script to test if a record exists before deciding how the code should continue. This allows handling error cases when a record doesn’t exist, creation of expected records, or an alternate handling path depending on whether the record exists or not. The call to setLimit is extremely important to maintaining the best performance by telling the database to stop searching after finding one matching record.

 * Handles conditional execution based on the existence of a user record
 * @param {Function} foundCallback - Function that is executed if the user record is found
 * @param {Function} notFoundCallback - Function that is executed if the user record is not found
function ifUserFound(foundCallback, notFoundCallback) {
    var tableName = 'sys_user';
    var user = new GlideRecord(tableName);
    user.addQuery('user_id', 'tltoulson');
    user.addQuery('active', true);
    user.setLimit(1); // Very important for performance since we only care about one record

    if (user.next()) {
    else {

 * @param {GlideRecord} user - The user record that has been found
function userFound(user) { 
    // Code to execute if a matching record exists

function userNotFound() {
    // Code to execute if a matching record does not exist

// This example will execute different code depending on whether a User ID is active or not
ifUserFound(userFound, userNotFound);