Useful Javascript Code For Servicenow
Useful Javascript Code For Servicenow
Useful Javascript Code For Servicenow
Contents
Background Information & Resources .......................................................................................................... 4
Lesson 1: Getting Started .............................................................................................................................. 5
1.1 First script............................................................................................................................................ 5
1.2 Example of server-side script .............................................................................................................. 5
1.3 Example of a client-side script ............................................................................................................ 6
Lesson 2: Statements and syntax .................................................................................................................. 7
2.1 When semicolons are required ........................................................................................................... 7
2.2 When semicolons are optional ........................................................................................................... 7
2.3 When to avoid semicolons .................................................................................................................. 7
Lesson 3: Variables........................................................................................................................................ 9
3.1 Simple variables & good/bad variable names .................................................................................... 9
3.2 Naming examples ................................................................................................................................ 9
Lesson 4: Simple Arithmetic Operators ...................................................................................................... 10
Lesson 5: Common Error Messages ............................................................................................................ 11
Lab 2 ............................................................................................................................................................ 11
Lesson 6: Strings.......................................................................................................................................... 12
Lesson 7: Special Characters ....................................................................................................................... 12
Lesson 8: Data Type Conversions................................................................................................................ 13
Lab 3: Instructions ....................................................................................................................................... 13
Lab 3: Solution ............................................................................................................................................ 14
Lesson 9: Commenting ................................................................................................................................ 15
Lesson 10: Comparisons.............................................................................................................................. 15
1
Lesson 11: The If Statement and Boolean Logic ......................................................................................... 16
11.1 If statements ................................................................................................................................... 16
11.2 Boolean logic tables ........................................................................................................................ 17
11.3 Boolean logic code examples .......................................................................................................... 18
Lesson 12: The Ternary Operator ............................................................................................................... 19
Lesson 13: The Switch Statement ............................................................................................................... 20
Lesson 14: Truthy/Falsy .............................................................................................................................. 22
Lab 4: Instructions ....................................................................................................................................... 22
Lab 4: Solution ............................................................................................................................................ 23
Lesson 15: The While Loop ......................................................................................................................... 24
15.1 Simple while loop ............................................................................................................................ 24
15.2 Breaking out of a while loop ........................................................................................................... 24
15.3 Continue - jumping back to the while condition............................................................................. 24
Lesson 16: The For Loop ............................................................................................................................. 25
Lesson 17: The Do-While Loop.................................................................................................................... 25
Lesson 18: Nested Loops............................................................................................................................. 26
Lab 5: Instructions ....................................................................................................................................... 26
Lab 5: Solution ............................................................................................................................................ 27
Lesson 19: Functions ................................................................................................................................... 28
19.1 Functions ......................................................................................................................................... 28
19.2 Function with a parameter ............................................................................................................. 28
19.3 Function with a return value........................................................................................................... 28
19.4 Local variables scope ...................................................................................................................... 29
19.5 - Global variables and local ............................................................................................................. 29
19.6 Self running function....................................................................................................................... 30
Lesson 20: Try/Catch/Finally Statements ................................................................................................... 31
20.1 Bad script w/o try/catch ................................................................................................................. 31
20.2 Trapping that error ......................................................................................................................... 31
20.3 And finally ….................................................................................................................................... 31
Lesson 21: Simple Database Query ............................................................................................................. 32
21.1 Get and display numbers on all incidents ....................................................................................... 32
21.2 Get and display numbers on all incidents v2 .................................................................................. 32
21.3 What is 'number’? ........................................................................................................................... 33
2
21.4 Getting a single record quickly........................................................................................................ 33
Lesson 22: Introduction to Arrays ............................................................................................................... 34
22.1 Making a simple array ..................................................................................................................... 34
22.2 Loops and arrays ............................................................................................................................. 34
Lesson 23: Array forEach............................................................................................................................. 35
Lesson 24: Common Array Methods........................................................................................................... 36
1. Common array methods/functions..................................................................................................... 36
2. join(string) ........................................................................................................................................... 36
3. shift() ................................................................................................................................................... 37
4. unshift ................................................................................................................................................. 38
5. splice ................................................................................................................................................... 38
6. slice ..................................................................................................................................................... 39
7. Reverse the elements of an array ....................................................................................................... 39
8. Getting the value................................................................................................................................. 40
Lesson 25: ServiceNow ArrayUtil ................................................................................................................ 41
Lab 6a: Instructions ..................................................................................................................................... 41
Lab 6a: Solution........................................................................................................................................... 42
Lab 6b: Instructions..................................................................................................................................... 42
Lab 6b: Solution .......................................................................................................................................... 43
Lesson 26: Introduction to Objects ............................................................................................................. 44
26.1 Simple Objects ................................................................................................................................ 44
26.2 Bracket notation ............................................................................................................................. 44
26.3 Shortcut: JSON format .................................................................................................................... 44
Lesson 27: Checking if an Object has a Property ........................................................................................ 45
‘hasOwnProperty’ method ..................................................................................................................... 45
Lesson 28: Finding All Properties in an Object............................................................................................ 45
Lesson 29: Arrays of Objects ....................................................................................................................... 46
Lesson 30: JSON Stringify and Parse ........................................................................................................... 47
30.1 Stringify and Parse .......................................................................................................................... 47
30.2 Parse example ................................................................................................................................. 49
Lab 7: Instructions ....................................................................................................................................... 49
Lab 7: Solution ............................................................................................................................................ 50
Lesson 31: More String Methods ................................................................................................................ 51
3
31.1 Find the position of a character or substring .................................................................................. 51
31.2 Use the position of a character/substring as a condition ............................................................... 51
31.3 Get a substring ................................................................................................................................ 51
31.4 Note: case matters with strings ...................................................................................................... 52
31.5 Using toUpper or toLower for better matching .............................................................................. 52
Lesson 32: Recursion................................................................................................................................... 53
Lesson 33: Classes ....................................................................................................................................... 54
33.1 Classes, Objects, and Prototypes .................................................................................................... 54
33.2 Initialize values ................................................................................................................................ 55
Lesson 34: Passing objects to functions ...................................................................................................... 56
Lesson 35: Class Inheritance ....................................................................................................................... 57
Lesson 36: Scripted REST APIs..................................................................................................................... 59
36.1 Simple scripted REST API (GET) resource ........................................................................................ 59
36.2 Scripted REST API with query parameters ...................................................................................... 59
36.3 Scripted REST API with path parameters ........................................................................................ 60
36.4 Scripted REST API (POST) with request body payload .................................................................... 60
36.5 Scripted REST API with POST and response .................................................................................... 61
Lab 8a: Instructions ..................................................................................................................................... 61
Lab 8a: Solution........................................................................................................................................... 62
Lab 8b: Instructions..................................................................................................................................... 62
Lab 8b: Solution .......................................................................................................................................... 63
Helpful Resources ....................................................................................................................................... 65
Overview/introductory video
4
Lesson 1: Getting Started
An introduction to what this video series is about (and not about), who it is for, and how to get started.
This video also includes examples that you can download and test for yourself to get started writing
JavaScript on the Now Platform.
This code does a database query for all the active task records, then prints the task number for each.
while (gr.next()) {
gs.info(gr.getValue('number'));
}
5
1.3 Example of a client-side script
To create a new client script that displays an alert whenever an incident form is loaded:
• Type is: onload (because that’s what the script template specifies)
• Add code:
function onLoad() {
alert('Current state value is: ' + g_form.getValue('state'));
}
• Click ‘Update’
• The alert will now display the current state whenever an incident form is loaded (e.g., via
Incident > All)
6
Lesson 2: Statements and syntax
This lesson covers the basics of JavaScript syntax and when semicolons should/shouldn’t be used.
BUT:
7
Function statements:
Exception:
for (var i=0; i < 10; i++) {/*actions*/} // Correct
for (var i=0; i < 10; i++;) {/*actions*/} // This will cause a syntax error
8
Lesson 3: Variables
This lesson demonstrates some simple scalar (or primitive) variable types, how to declare and set them
and best practices for naming your variables.
Rather than variable names such as ‘person’, it’s best to put the variable type on the end of the var
name, e.g.:
9
Lesson 4: Simple Arithmetic Operators
This lesson covers some simple arithmetic operators to help you understand how to add, subtract,
multiply, divide, and modulo (the remainder of division). It also includes some time saving shortcuts.
// Assignment
var a = 12;
var b = 3;
// Addition
gs.info(2 + 2);
gs.info(a + 2);
b = b + 2;
// b += 2; // shorthand for the line above
gs.info(a + b);
// Increment by 1
a++; /* or ‘++a;’ is the same thing */ gs.info(a);
// Decrement by 1
b--; gs.info(b);
// Multiply
gs.info(a * b);
// Division
gs.info(a / b);
var c = (5 + 4) * 2;
gs.info(c); // output is 18
10
Lesson 5: Common Error Messages
Lesson 5 covers some common error messages you may encounter while writing JavaScript and how to
overcome them.
gs.info(myUnknownVariable);
ga.info('Hello, world!);
Lab 2
This lab exercise challenges you to test your arithmetic skills to get the right answer.
Instructions:
What is 3 + 2 * 5?
Solution:
11
Lesson 6: Strings
Introducing strings, the length property, and concatenating strings together.
// \n = new line
// \t = tab
// \\ = backslash
// \' = single quote
// \" = double quote
12
Lesson 8: Data Type Conversions
Lesson 8 shows you how to convert an integer to a string, a string to an integer, and how to determine
what type of variable you have if you're not sure.
var i = 5;
var iStr = i.toString(); // convert an integer to a string
Lab 3: Instructions
Create three string variables. Print the length of each string. concatenate them together with a new line
character and save to a new variable. Print the new variable and length of the new variable.
13
Lab 3: Solution
This video demonstrates the answer to the lab assignment given in lesson 8.
Instructions:
Create three string variables. Print the length of each string. concatenate them together with a new line
character and save to a new variable. Print the new variable and length of the new variable.
Solution:
gs.info('allStrings=' + allStrings);
Output:
*** Script: length1 = 5
Tomasi
JavaScript
14
Lesson 9: Commenting
Lesson 9 takes explains what comments are and why you want to use them and how they can be
formatted. It also includes some best practices for commenting.
/*
This is a multi-line comment.
This code is commented out!
var name = 'Chuck';
*/
var a = 0;
var b = 1;
gs.info(a < b); // output: true or false
var n = '3';
var i = 3;
gs.info(n == i); // Output: true (same value) – because JavaScript is a ‘loosely
typed language’
gs.info(n === i); // Checks for equality of value AND data type
15
Lesson 11: The If Statement and Boolean Logic
In lesson 11, you learn about the if statement for controlling the flow of your JavaScript. This video also
takes a look at basic Boolean logic with AND, OR, and NOT operators to make more complex logical
comparisons.
11.1 If statements
var a = 1; var b = 3; var c = 5;
if (a < b)
gs.info('a is less than b');
var bool = a < b;
if (bool) {
gs.info ('a is less than b');
} else { … }
// else
if (a < b)
gs.info('a is less than b');
else
gs.info('a is greater than or equal to b');
if (a < b)
if (b < c)
gs.info('a b c are in order');
16
11.2 Boolean logic tables
// +---------+---------+---------+
// +---------+---------+---------+
// +---------+---------+---------+
// +---------+---------+---------+
// +---------+---------+---------+
// | OR | true | false |
// +---------+---------+---------+
// +---------+---------+---------+
// +---------+---------+---------+
17
11.3 Boolean logic code examples
var a = 1;
var b = 3;
var c = 5;
if (b > a || b > c)
gs.info ('b is greater than one of them.');
if (bool)
gs.info('Valve is currently open');
18
Lesson 12: The Ternary Operator
How to create a short method of the if/else statement.
19
Lesson 13: The Switch Statement
The switch statement is a cleaner way to do if/else if/else if/else on the same variable.
var level = 5;
var message = '';
if (level == 0)
message = 'Empty';
else if (level == 1 || level == 2)
message = 'Low';
else if (level == 3)
message = 'Medium';
else if (level == 4)
message = 'High';
else if (level == 5)
message = 'Full';
else
message = 'Uh-oh';
gs.info('Level=' + level + ' status=' + message);
20
Using the switch statement:
var level = 5;
var message = '';
switch (level) { //can only be an integer or a string
case 0:
message = 'Empty';
break;
case 1:
case 2:
message = 'Low';
break;
case 3:
message = 'Medium';
break;
case 4:
message = 'High';
break;
case 5:
message = 'Full';
break;
default:
message = 'Uh-oh!';
}
21
Lesson 14: Truthy/Falsy
Lesson 14 takes a look at what makes Boolean, integer, and even string variables true or false in an
condition.
Lab 4: Instructions
Create a script that takes a string variable “Hello world” and translates it to at least 3 different languages
based on a 'language' variable.
22
Lab 4: Solution
Link to Lab 4 solution video
Instructions:
Create a script that takes a string variable “Hello world” and translates it to at least 3 different languages
based on a 'language' variable.
Solution:
switch (language) {
case 'German':
toString = 'Hallo Welt';
break;
case 'French':
toString = 'Bonjour le monde';
break;
case 'Spanish':
toString = 'Hola Mundo';
break;
default:
toString = 'Hello, world';
}
Output:
Hello world in German ==> Hallo Welt
23
Lesson 15: The While Loop
Link to lesson 15 video
24
Lesson 16: The For Loop
This lesson explains and demonstrates how to use the for loop to run one or more statements multiple
times.
var i = 0;
gs.info('start');
do {
gs.info('i=' + i);
++i;
} while (i < 5);
gs.info('done i=' + i);
25
Lesson 18: Nested Loops
Explains and demonstrates how to use a loop within a loop. While this example shows two for loops, any
loop can be placed inside another. However, there are some considerations to take when using nested
loops.
Lab 5: Instructions
Create a script that creates 5 teams of 4 people and assigns a unique identifier to each team member.
The script should display the team number, person number, and identifier for that person/team.
26
Lab 5: Solution
Instructions:
Create a script that creates 5 teams of 4 people and assigns a unique identifier to each team member.
The script should display the team number, person number, and identifier for that person/team.
Solution:
var id = 1;
++id;
27
Lesson 19: Functions
Lesson 19 introduces you to the topic of functions. You will learn when and why you might want to build
a function, how to pass information in to a function and how to get information out. It also
demonstrates how to call a function from within another function.
19.1 Functions
function toCelsius(fahrenheit) {
gs.info(c);
}
toCelsius(32);
toCelsius(100);
function toCelsius(fahrenheit) {
return (5 / 9) * (fahrenheit - 32); // return – used to get a value out of a
function
}
var c = toCelsius(32);
gs.info(c);
c = toCelsius(212);
gs.info(c);
28
19.4 Local variables scope
function toCelsius(fahrenheit) {
function toCelsius(f) {
var c = (5 / 9) * (f - 32);
return c;
}
function toFahrenheit(c) {
var f = c * 9 / 5 + 32;
return f;
}
function convertTemp(temp) {
29
19.6 Self running function
(function() {
// Local variable
i = 10; // uh-oh, forgot the var!
gs.info('i=' + i);
}());
i = 3;
gs.info('i=' + i);
30
Lesson 20: Try/Catch/Finally Statements
Lesson 20 shows you how to safeguard your code against rogue errors so it continues to run using the
try/catch/finally construct.
try {
for (var i = 0; i < 5; i++) {
gs.info('i=' + i + ' answer=' + answer);
}
} catch (e) {
gs.error ('Uh-oh ' + e.message); // error output
} // error will also appear in ‘System Logs - All’
gs.info('done');
try {
for (var i = 0; i < 5; i++) {
gs.info('i=' + i + ' answer=' + answer);
}
} catch (e) {
gs.error('Uh-oh ' + e.message);
} finally {
gs.info('done');
}
31
Lesson 21: Simple Database Query
This lesson shows you some basic operations to retrieve records from the database using GlideRecord
on ServiceNow. This applies some of the earlier concepts with functionality specific to the Now Platform.
while (incGr.next()) {
gs.info(incGr.getValue('number'));
}
32
21.3 What is 'number’?
if (incGr.next()) {
var dotNumber = incGr.number;
var gvNumber = incGr.getValue('number');
gs.info('dotNumber=' + typeof dotNumber + ' gvNumber=' + typeof gvNumber);
}
if (incGr.get('965c9e5347c12200e0ef563dbb9a7156')) {
gs.info(incGr.getValue('number'));
}
// Or:
if (incGr.get('number', 'INC0000059')) {
gs.info(incGr.getValue('sys_id'));
}
33
Lesson 22: Introduction to Arrays
Introducing the concept of arrays. Arrays are a great way to keep a list of the same data type (integer,
string, etc.) in memory and address them as one unit or individually.
A shorter way:
34
Lesson 23: Array forEach
This lesson demonstrates a unique way to create a loop using an array with the forEach method.
Embedded forEach:
35
Lesson 24: Common Array Methods
Lesson 24 demonstrates some of the common things you can do with arrays to manage the elements
they contain.
or:
2. join(string)
Or:
list.push('Dave');
list.push('Andrew');
gs.info('push: list=' + list.join(', '));
36
pop()
The last thing pushed onto the stack is the first thing popped off.
Output:
3. shift()
Output:
37
4. unshift
Output:
*** Script: new length=5 unshift() list=Jason, Andrew, Chuck, Kreg, Stacey
5. splice
Notation:
Output:
38
6. slice
Notation:
slice(start, end)
Output:
Output:
39
8. Getting the value
while (incGr.next()) {
list.push(incGr.getValue(fName));
++ countReturned;
}
gs.info('list=\n' + list.join('\n'));
gs.info(countReturned);
Output:
40
Lesson 25: ServiceNow ArrayUtil
Lesson 25 builds on lesson 24 with some additional array utilities provided by ServiceNow.
ArrayUtil is part of a ServiceNow Script Include. To review the script, etc. go to: System Definitions >
Script Includes, search term: ‘=ArrayUtil’
Output:
41
Lab 6a: Solution
Instructions:
Create a script to accept a table name and return a list records display values.
Solution:
function listRecords(tableName) {
while (recGr.next()) {
answer.push(recGr.getDisplayValue());
}
return answer;
}
gs.info(listRecords('incident').join('\n'));
42
Lab 6b: Solution
Instructions:
Solution:
while (recGr.next()) {
answer.push(recGr.getDisplayValue());
}
return answer;
}
gs.info(listRecords('incident', 10).join('\n'));
43
Lesson 26: Introduction to Objects
Introducing the concept of JavaScript objects: what they are, and how to create and manage them.
Initializing and setting name/value pairs at the same time: using JSON (JavaScript Object Notation)
format declaration:
var vehicle = {
"year" : 2018, // It’s best to use double quotes, although single quotes may work
"make" : "Toyota",
"model" : "Sienna"
};
gs.info(vehicle['year'] + ' ' + vehicle['make'] + ' ' + vehicle['model']);
44
Lesson 27: Checking if an Object has a Property
How to check if an object has a given property and why this would be useful to know.
‘hasOwnProperty’ method
var vehicle = {
"year" : 2018,
"make" : "Toyota",
"model" : "Sienna"
};
gs.info(vehicle.hasOwnProperty("year")); // <== true
gs.info(vehicle.hasOwnProperty("price")); // <== false
var vehicle = {
"year" : 2018,
"make" : "Toyota",
"model" : "Sienna"
};
for (var key in vehicle) {
gs.info('key=' + key + ' value=' + vehicle[key]);
}
45
Lesson 29: Arrays of Objects
This lesson combines the lessons on arrays AND objects to create arrays OF objects and why they are so
useful.
var bookList = [
{
"title" : "Harry Potter and the Chamber of Secrets",
"author" : "J.K. Rowling"
},
{
"title" : "Moby Dick",
"author" : "Herman Melville"
},
{
"title" : "A Tale of Two Cities",
"author" : "Charles Dickens"
}
];
var len = bookList.length; // Tells us: how many books are in the
library.
gs.info('Last author=' + bookList[len - 1].author); // ‘len - 1’ because len is 3
but array // numbering start at 0 and stops at 2
for (var i = 0; i < len; i++) {
var book = bookList[i];
gs.info(i + ' - Title: ' + book.title + ' - Author: ' + book.author);
}
46
Lesson 30: JSON Stringify and Parse
Lesson 30 introduces JSON.stringify() and JSON.parse() to translate objects to strings and back again.
Watch the video to find out why this is such a powerful JavaScript feature.
var bookList = [
{
"title" : "Harry Potter and the Chamber of Secrets",
"author" : "J.K. Rowling"
},
{
"title" : "Moby Dick",
"author" : "Herman Melville"
},
{
"title" : "A Tale of Two Cities",
"author" : "Charles Dickens"
}
];
gs.info(bookList);
Output:
47
var bookListStr = JSON.stringify(bookList);
gs.info(bookListStr);
Output:
Output:
48
30.2 Parse example
gs.info('length=' + libraryStr.length);
var libraryObj = JSON.parse(libraryStr);
gs.info('length=' + libraryObj.length);
gs.info(JSON.stringify(libraryObj, null, 4)); // 4 spaces of indentation, see link below
Output:
Lab 7: Instructions
Update your previous lab to return the sys_id and display value of the records you found using an array
of objects. Return an array of objects.
49
Lab 7: Solution
Instructions:
Update your previous lab to return the sys_id and display value of the records you found using an array
of objects. Return an array of objects.
Solution:
while (recGr.next()) {
var obj = {};
obj.display_value = recGr.getDisplayValue();
obj.sys_id = recGr.getUniqueValue();
answer.push(obj);
}
return answer;
}
50
Lesson 31: More String Methods
A look at more string methods to help manage this fundamental data type in JavaScript.
51
31.4 Note: case matters with strings
52
Lesson 32: Recursion
Recursion is the concept of a function calling itself. While this may seem like a crazy idea, it is a very
powerful tool when dealing with hierarchical data like business services. However, there are some things
about recursion you need to pay attention to, or you could find yourself in an infinite loop.
An example of where recursion is used is anywhere there is a parent-child relationship with records (e.g.
tasks, CIs, etc.) You can recurse "up" the CI tree to find the parent service, or recurse "down" to start
with a service and ensure you find all the child/related CIs.
It’s a similar concept to the way Service Watch works for business service discovery.
The following function calculates the factorial of x (often written as ‘x!’) e.g. 5! = 5 x 4 x 3 x 2 x 1 = 120
function factorial(x) {
// TERMINATION
if (x < 0)
return;
// BASE
if (x === 0) // === not only compares the value, but also the type.
// For example: "1" == 1 is true, whereas "1" === 1 is false
// because a string and an integer are different types.
return 1;
// RECURSION
return x * factorial(x - 1);
gs.info(factorial(3)); // Returns 6
53
Lesson 33: Classes
How to improve testing and reduce maintenance by creating object templates known as classes. Go
beyond properties and add functions to your objects!
setLastName : function(str) {
this.lastName = str;
},
getDisplayName : function() {
return this.firstName + ' ' + this.lastName;
},
type: person
};
54
33.2 Initialize values
setFirstName : function(str) {
this.firstName = str;
},
setLastName : function(str) {
this.lastName = str;
},
getDisplayName : function() {
return this.firstName + ' ' + this.lastName;
},
type: 'person'
};
55
Lesson 34: Passing objects to functions
How to combine the power of objects with functions to go beyond basic data types being pass in and
out of functions.
debugObject : function(obj) {
type: 'item'
};
var myObj = {
"type" : "vehicle",
"engine" : true,
"wheels" : 4,
"state" : "allocated"
};
var myItem = new item();
myItem.debugObject(myObj);
56
Lesson 35: Class Inheritance
Creating classes based on existing classes to extend or override functionality, while avoiding duplicate
code across classes.
register : function() {
gs.info(this.getDisplayName() + ' registered!');
},
info : function() {
gs.info('Vehicle info: TBD');
},
getDisplayName : function() {
},
type: 'vehicle'
};
57
findDealer : function() {
gs.info('Find dealer is not yet implemented');
},
info : function() {
gs.info('Car info: TBD');
},
type: 'car'
});
58
Lesson 36: Scripted REST APIs
This lesson builds on the skills you've learned thus far to create a custom REST API using a ServiceNow
Scripted REST API. You'll learn about REST services and resources as well as how to pass information to
your REST resource and return a result. This lesson also covers the basics of the REST API Explorer to
help test your code.
})(request, response);
return answer;
})(request, response);
59
36.3 Scripted REST API with path parameters
return answer;
})(request, response);
return answer;
})(request, response);
60
36.5 Scripted REST API with POST and response
return response;
})(request, response);
https://www.youtube.com/watch?v=48aBJqdC6xI
61
Lab 8a: Solution
Instructions:
Rebuild the previous lab as a scripted REST API. Use Query parameters to accept the table name and
limit. Return the array of objects in the response body. Get table record display values and sys_ids.
Solution:
while (recGr.next()) {
var obj = {};
obj.display_value = recGr.getDisplayValue();
obj.sys_id = recGr.getUniqueValue();
answer.push(obj);
}
response.setBody(answer);
})(request, response);
62
Lab 8b: Solution
Instructions:
Rebuild the previous lab using a script include for the core logic.
Solution:
while (recGr.next()) {
var obj = {};
obj.display_value = recGr.getDisplayValue();
obj.sys_id = recGr.getUniqueValue();
answer.push(obj);
}
return answer;
},
type: 'SNJS'
};
63
Test the script include using the following code:
• Take the Record Finder REST API, add a new resource to it, called ‘Lab8b’
• Relative path = ‘/Lab8b’
• Add the following script:
response.setBody(list);
})(request, response);
64
Helpful Resources
This video provides some final notes and helpful resources to help you continue learning JavaScript on
the Now Platform.
Resources:
• Codecademy.com (JavaScript)
• W3Schools.com (JavaScript)
• ServiceNow Docs
• TechNow webinars
• ServiceNow Community
Visual Studio Code is a code editor redefined and optimized for building and debugging modern web
and cloud applications.
https://code.visualstudio.com/
https://www.google.com/search?rlz=1C1CHZL_enNZ844NZ844&q=using+Visual+Studio+Code+with+ser
vicenow&spell=1&sa=X&ved=2ahUKEwjt6aTvvJ3-AhXft1YBHYDvADkQkeECKAB6BAgIEAE
https://docs.servicenow.com/bundle/tokyo-application-
development/page/build/applications/concept/vs-code.html
65