├── README.md ├── Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi ├── Lab Solutions │ ├── Lab 2.js │ ├── Lab 3 .js │ ├── Lab 4.js │ ├── Lab 5.js │ ├── Lab 6a.js │ ├── Lab 6b.js │ ├── Lab 7.js │ ├── Lab 8a.js │ ├── Lab 8b-ScriptInclude-Test.js │ ├── Lab 8b-ScriptInclude.js │ └── Lab 8b.js ├── Lesson_01 │ ├── L01S01.js │ ├── L01S02.js │ └── L01S03.js ├── Lesson_02 │ └── L0201.js ├── Lesson_03 │ └── L0301.js ├── Lesson_04 │ └── L04S01.js ├── Lesson_05 │ └── L05S01.js ├── Lesson_06 │ └── L06S01.js ├── Lesson_07 │ └── L07S01.js ├── Lesson_08 │ └── L0801.js ├── Lesson_09 │ └── L09S01.js ├── Lesson_10 │ └── L10S01.js ├── Lesson_11 │ ├── L11S01.js │ └── L11S02.js ├── Lesson_12 │ └── L12S01.js ├── Lesson_13 │ ├── L13S01.js │ └── L13S02.js ├── Lesson_14 │ ├── L14S01.js │ ├── L14S02.js │ └── L14S03.js ├── Lesson_15 │ ├── L15S01.js │ ├── L15S02.js │ └── L15S03.js ├── Lesson_16 │ └── L16S01.js ├── Lesson_17 │ └── L17S01.js ├── Lesson_18 │ └── L18S01.js ├── Lesson_19 │ ├── L19S01.js │ ├── L19S02.js │ ├── L19S03.js │ ├── L19S04.js │ ├── L19S05.js │ └── L19S06.js ├── Lesson_20 │ ├── L20S01.js │ ├── L20S02.js │ └── L20S03.js ├── Lesson_21 │ ├── L21S01.js │ ├── L21S02.js │ ├── L21S03.js │ └── L21S04.js ├── Lesson_22 │ ├── L22S01.js │ ├── L22S02.js │ └── L22S03.js ├── Lesson_23 │ ├── L23S01.js │ ├── L23S02.js │ └── L23S03.js ├── Lesson_24 │ ├── L24S01.js │ ├── L24S02.js │ ├── L24S03.js │ ├── L24S04.js │ ├── L24S05.js │ ├── L24S06.js │ ├── L24S07.js │ └── L24S08.js ├── Lesson_25 │ └── L25S01.js ├── Lesson_26 │ ├── L26S01.js │ ├── L26S02.js │ └── L26S03.js ├── Lesson_27 │ └── L27S01.js ├── Lesson_28 │ └── L28S01.js ├── Lesson_29 │ └── L29S01.js ├── Lesson_30 │ ├── L30S01.js │ └── L30S02.js ├── Lesson_31 │ ├── L31S01.js │ ├── L31S02.js │ ├── L31S03.js │ ├── L31S04.js │ └── L31S05.js ├── Lesson_32 │ └── L32S01.js ├── Lesson_33 │ ├── L33S01.js │ └── L33S02.js ├── Lesson_34 │ └── L34S01.js ├── Lesson_35 │ └── L35S01.js └── Lesson_36 │ ├── L36S01.js │ ├── L36S02.js │ ├── L36S03.js │ ├── L36S04.js │ └── L36S05.js ├── Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque ├── Lesson_01 │ ├── L01S01.js │ ├── L01S02.js │ ├── L01S03.js │ └── Lesson_01_Exercise.js ├── Lesson_02 │ ├── L02S01.js │ ├── L02S02.js │ └── Lesson_02_Exercise.js ├── Lesson_03 │ └── L03S01.js ├── Lesson_04 │ ├── L04S01.js │ └── Lesson_04_Exercise.js ├── Lesson_05 │ ├── L05S01.js │ └── Lesson_05_Exercise.js ├── Lesson_06 │ ├── L06S01.js │ ├── L06S02.js │ ├── L06S03.js │ ├── L06S04.js │ ├── L06S05.js │ └── Lesson_06_Exercise.js ├── Lesson_07 │ ├── L07S01.js │ └── Lesson_07_Exercise.js ├── Lesson_08 │ ├── L0801.js │ ├── L0802.js │ └── L0803.js ├── Lesson_09 │ ├── L09S01.js │ ├── L09S02.js │ ├── L09S03.js │ └── Lesson_09_Exercise.js ├── Lesson_10 │ ├── L10S01.js │ ├── L10S02.js │ └── L10S03.js ├── Lesson_11 │ ├── L11S01.js │ └── Lesson_11_Exercise.js ├── Lesson_12 │ ├── L12S01.js │ └── L12S02.js ├── Lesson_13 │ ├── L13S01.js │ └── L13S02.js └── Lesson_14 │ ├── L14S01.js │ ├── L14S02.js │ ├── L14S03.js │ └── Lesson_14_exercise.js └── Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque ├── Lesson_01 ├── L01S01.js ├── L01S02.js └── L01S03.js ├── Lesson_02 └── L02S01.js ├── Lesson_03 ├── L03S01.js ├── L03S02.js └── L03S03.js ├── Lesson_04 ├── L04S01.js ├── L04S02.js └── L04S03.js ├── Lesson_05 └── L05S01.js ├── Lesson_06 ├── L06S01.js └── L06S02.js ├── Lesson_07 └── L07S01.js ├── Lesson_08 └── L08S01.js ├── Lesson_09 ├── L09S01.js └── L09S02.js ├── Lesson_10 ├── L10S01.js └── L10S02.js ├── Lesson_11 ├── L11S01.js └── L11S02.js ├── Lesson_12 ├── L12S01.js └── L12S02.js ├── Lesson_13 ├── L13S01.js └── L13S02.js ├── Lesson_14 ├── L14S01.js └── L14S02.js ├── Lesson_15 └── L15S01.js ├── Lesson_16 ├── L16S01.js └── L16S02.js ├── Lesson_17 ├── L17S01.js └── L17S02.js ├── Lesson_18 ├── L18S01.js └── L18S02.js ├── Lesson_19 ├── L19S01.js └── L19S02.js ├── Lesson_20 ├── L20S01.js └── L20S02.js ├── Lesson_21 ├── L21S01.js └── L21S02.js ├── Lesson_22 ├── L22S01.js └── L22S02.js ├── Lesson_23 ├── L23S01.js └── L23S02.js ├── Lesson_24 ├── L24S01.js └── L24S02.js └── Scrapped_exercises ├── Lesson_00_what_happend.md ├── Lesson_01_Exercise.js ├── Lesson_02_Exercise.js ├── Lesson_03_Exercise.js ├── Lesson_04_Exercise.js ├── Lesson_05_Exercise.js ├── Lesson_06_Exercise.js ├── Lesson_07_Exercise.js ├── Lesson_08_Exercise.js ├── Lesson_09_Exercise.js ├── Lesson_10_Exercise.js ├── Lesson_11_Exercise.js ├── Lesson_12_Exercise.js ├── Lesson_13_Exercise.js ├── Lesson_14_Exercise.js ├── Lesson_16_Exercise.js ├── Lesson_17_Exercise.js ├── Lesson_19_Exercise.js ├── Lesson_20_Exercise.js ├── Lesson_21_Exercise.js ├── Lesson_22_Exercise.js ├── Lesson_23_Exercise.js └── Lesson_24_Exercise.js /README.md: -------------------------------------------------------------------------------- 1 | # Welcome to Learn JavaScript on the Now Platform! 2 | 3 | This repository contains examples used in the video series in folders corresponding to the lessons. 4 | 5 | ## Sections 6 | 7 | 1. The original series can be found here: [Learn JavaScript on the Now Platform with Chuck Tomasi](https://www.youtube.com/watch?v=62Nabpb94Jw&list=PL3rNcyAiDYK2_87aRvXEmAyD8M9DARVGK&index=1) 8 | 2. The follow-up series can be found here: [Learn MORE JavaScript on the ServiceNow Platform with Earl Duque](https://www.youtube.com/watch?v=OBRQtWk_nvg&list=PL3rNcyAiDYK2_87aRvXEmAyD8M9DARVGK&index=55) 9 | 3. And a series specifically on ECMAScript 2021 can be found here: [Let's learn ECMAScript 2021 (ES2021) with Earl Duque](https://www.youtube.com/watch?v=d5gJtBiqcAM&list=PL3rNcyAiDYK1fUOYO83KOfF-NriBRAERV&index=1). [or watch this video, lol](https://www.servicenow.com/events/knowledge/2024/sessions/-template-literals-let-and----javascript-ecmascript-2021-and-you.html) 10 | 11 | Scripts use the naming structure **L(lesson#)S(script#).js**. 12 | Example, L09S01.js refers to Lesson 9, script example 1. 13 | Solutions to lab exercises can also be found in the *Lab Solutions* folder. 14 | 15 | # Helpful resources mentioned in this series 16 | 17 | * [Codecademy.com (JavaScript)](https://www.codecademy.com/catalog/language/javascript) 18 | * [W3Schools.com (Javascript)](https://www.w3schools.com/js/default.asp) 19 | * [ServiceNow Developer Program](https://developer.servicenow.com) 20 | * [Scripting in ServiceNow Fundamentals](https://www.servicenow.com/services/training-and-certification/scripting-in-servicenow-training.html) 21 | * [ServiceNow Docs](https://docs.servicenow.com) 22 | * [ServiceNow Technical Best Practices](https://developer.servicenow.com/dev.do#!/guides/quebec/now-platform/tpb-guide/scripting_technical_best_practices) 23 | * [TechNow webinars](https://devlink.sn/technow) 24 | * [ServiceNow Community](https://community.servicenow.com) 25 | * [Stephen Bell's Scripting Best Practices Videos](https://www.youtube.com/user/ServiceNowCommunity/search?query=scripting+best+practices) 26 | * [Regular Expression Documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions) 27 | * [Online RegEx Testing](https://regexr.com/) 28 | * [Script Design Problems](https://codecreative.io/blog/interface-design-patterns-for-script-includes/) 29 | -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lab Solutions/Lab 2.js: -------------------------------------------------------------------------------- 1 | // 2 | // Lab 2 3 | // 4 | // What is 3 + 2 * 5? 5 | // 6 | gs.info(3 + 2 * 5); // 13 -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lab Solutions/Lab 3 .js: -------------------------------------------------------------------------------- 1 | // 2 | // Lab 3 3 | // 4 | // Create a three string variables. 5 | // Print the length of each string 6 | // concatenate them together with a new line character and save to a new variable 7 | // Print the new variable and length of the new variable 8 | // 9 | var string1 = 'Chuck'; 10 | var string2 = 'Tomasi'; 11 | var string3 = 'JavaScript'; 12 | gs.info('length1 = ' + string1.length); 13 | gs.info('length2 = ' + string2.length); 14 | gs.info('length3 = ' + string3.length); 15 | 16 | var allStrings = string1 + '\n' + string2 + '\n' + string3; 17 | gs.info('allStrings=' + allStrings); 18 | gs.info('length of allStrings=' + allStrings.length); 19 | 20 | /* 21 | Output from Scripts - background 22 | 23 | *** Script: length1 = 5 24 | *** Script: length2 = 6 25 | *** Script: length3 = 10 26 | *** Script: allStrings=Chuck 27 | Tomasi 28 | JavaScript 29 | *** Script: length of allStrings=23 30 | */ -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lab Solutions/Lab 4.js: -------------------------------------------------------------------------------- 1 | // Lab 4: 2 | // Create a script that takes a string variable "Hello world" 3 | // and translates it to at least 3 different languages 4 | // based on a 'language' variable. 5 | // Make the default language English if a match isn't found. 6 | 7 | var language = 'German'; 8 | var fromString = 'Hello world'; 9 | var toString = ''; 10 | 11 | switch (language) { 12 | case 'German': 13 | toString = 'Hallo Welt'; 14 | break; 15 | case 'French': 16 | toString = 'Bonjour le monde'; 17 | break; 18 | case 'Spanish': 19 | toString = 'Hola Mundo'; 20 | break; 21 | default: 22 | toString = 'Hello, world'; 23 | } 24 | 25 | gs.info(fromString + ' in ' + language + ' ==> ' + toString); 26 | 27 | -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lab Solutions/Lab 5.js: -------------------------------------------------------------------------------- 1 | // 2 | // Lab 5: 3 | // Create a script that creates 5 teams of 4 people 4 | // and assigns a unique identifier to each team member. 5 | // The script should display the team number, 6 | // person number, and identifier for that person/team. 7 | // Avoid displaying zeros for a better user experience. 8 | // 9 | 10 | var id = 1; 11 | for (var team = 0; team < 5; team++) { 12 | for (var person = 0; person < 4; person++) { 13 | gs.info('id=' + id + ' team=' + team+1 + ' person=' + person+1); 14 | ++id; 15 | } 16 | } -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lab Solutions/Lab 6a.js: -------------------------------------------------------------------------------- 1 | // 2 | // Lab 6a: Create a script to accept a table name and 3 | // return a list records display values. 4 | // Hint: use GlideRecord.getDisplayValue() 5 | // 6 | // @param tableName - name of table to query 7 | // @return array - list of record display values 8 | // 9 | function listRecords(tableName) { 10 | 11 | var answer = []; 12 | var recGr = new GlideRecord(tableName); 13 | recGr.query(); 14 | 15 | while (recGr.next()) { 16 | answer.push(recGr.getDisplayValue()); 17 | } 18 | 19 | return answer; 20 | } 21 | 22 | gs.info(listRecords('incident').join('\n')); 23 | -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lab Solutions/Lab 6b.js: -------------------------------------------------------------------------------- 1 | // 2 | // Lab 6b: Update your previous script to accept a limit parameter. 3 | // Hint: use GlideRecord.setLimit() 4 | // 5 | // @param tableName - name of table to query 6 | // @param limit - integer > 0 7 | // @return array - list of record display values 8 | // 9 | function listRecords(tableName, limit) { 10 | 11 | var answer = []; 12 | var recGr = new GlideRecord(tableName); 13 | if (limit && limit > 0) { 14 | recGr.setLimit(limit); 15 | } 16 | recGr.query(); 17 | 18 | while (recGr.next()) { 19 | answer.push(recGr.getDisplayValue()); 20 | } 21 | 22 | return answer; 23 | } 24 | 25 | gs.info(listRecords('incident', 10).join('\n')); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lab Solutions/Lab 7.js: -------------------------------------------------------------------------------- 1 | // 2 | // Lab 7: 3 | // Update your previous lab to return the sys_id and 4 | // display value of the records you found using an array of objects. 5 | // Return an array of objects. 6 | // 7 | // @param tableName - name of table to query 8 | // @param limit - integer > 0 9 | // @return array of objects 10 | // { 11 | // "display_value" : , 12 | // "sys_id" : 13 | // } 14 | // 15 | function listRecords(tableName, limit) { 16 | 17 | var answer = []; 18 | var recGr = new GlideRecord(tableName); 19 | if (limit && limit > 0) { 20 | recGr.setLimit(limit); 21 | } 22 | recGr.query(); 23 | 24 | while (recGr.next()) { 25 | var obj = {}; 26 | obj.display_value = recGr.getDisplayValue(); 27 | obj.sys_id = recGr.getUniqueValue(); 28 | answer.push(obj); 29 | } 30 | 31 | return answer; 32 | } 33 | 34 | var list = listRecords('incident', 10); 35 | gs.info(JSON.stringify(list, null, 4)); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lab Solutions/Lab 8a.js: -------------------------------------------------------------------------------- 1 | // 2 | // Lab 8a - Rebuild the previous lab as a scripted REST API 3 | // Use Query parameters to accept the table name and limit 4 | // Return the array of objects in the response body 5 | // 6 | // Get table record display values and sys_ids 7 | // 8 | (function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) { 9 | 10 | var queryParams = request.queryParams; 11 | var tableName = queryParams.tableName; 12 | var limit = queryParams.limit; 13 | 14 | var answer = []; 15 | var recGr = new GlideRecord(tableName); 16 | 17 | if (limit && limit > 0) { 18 | recGr.setLimit(limit); 19 | } 20 | recGr.query(); 21 | 22 | while (recGr.next()) { 23 | var obj = {}; 24 | obj.display_value = recGr.getDisplayValue(); 25 | obj.sys_id = recGr.getUniqueValue(); 26 | answer.push(obj); 27 | } 28 | 29 | response.setBody(answer); 30 | 31 | })(request, response); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lab Solutions/Lab 8b-ScriptInclude-Test.js: -------------------------------------------------------------------------------- 1 | // 2 | // Lab 8b Script Include Test Script 3 | // 4 | var list = new SNJS().getRecords('problem', 5); 5 | gs.info(list.length); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lab Solutions/Lab 8b-ScriptInclude.js: -------------------------------------------------------------------------------- 1 | var SNJS = Class.create(); 2 | SNJS.prototype = { 3 | initialize: function() { 4 | }, 5 | 6 | getRecords : function(tableName, limit) { 7 | 8 | var answer = []; 9 | var recGr = new GlideRecord(tableName); 10 | 11 | if (limit && limit > 0) { 12 | recGr.setLimit(limit); 13 | } 14 | recGr.query(); 15 | 16 | while (recGr.next()) { 17 | var obj = {}; 18 | obj.display_value = recGr.getDisplayValue(); 19 | obj.sys_id = recGr.getUniqueValue(); 20 | answer.push(obj); 21 | } 22 | 23 | return answer; 24 | 25 | }, 26 | 27 | type: 'SNJS' 28 | }; -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lab Solutions/Lab 8b.js: -------------------------------------------------------------------------------- 1 | // 2 | // Lab 8b - Rebuild the previous lab using a script include for the core logic 3 | // Use Query parameters to accept the table name and limit 4 | // Return the array of objects in the response body 5 | // 6 | // Get table record display values and sys_ids 7 | // 8 | (function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) { 9 | 10 | var queryParams = request.queryParams; 11 | var tableName = queryParams.tableName; 12 | var limit. = queryParams.limit; 13 | 14 | var list = new SNJS().getRecords(tableName, limit); 15 | 16 | response.setBody(list); 17 | 18 | })(request, response); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_01/L01S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L01S01 - first script 3 | // 4 | gs.info('Hello, world!'); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_01/L01S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L01S02 - example server side script 3 | // 4 | var gr = new GlideRecord('task'); 5 | gr.addActiveQuery(); 6 | gr.query(); 7 | 8 | while (gr.next()) { 9 | gs.info(gr.getValue('number')); 10 | } -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_01/L01S03.js: -------------------------------------------------------------------------------- 1 | // 2 | // L01S03 - example client side script 3 | // 4 | function onLoad() { 5 | 6 | alert('Current state value is: ' + g_form.getValue('state')); 7 | 8 | } -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_02/L0201.js: -------------------------------------------------------------------------------- 1 | // 2 | // L02S01 - semicolon example 3 | // 4 | 5 | // Required: 6 | var i = 0; i++ // <-- semicolon obligatory 7 | // (but optional before newline) 8 | var i = 0 // <-- semicolon optional 9 | i++ // <-- semicolon optional 10 | 11 | // Optional: 12 | var i; // variable declaration 13 | i = 5; // value assignment 14 | i = i + 1; // value assignment 15 | i++; // same as above 16 | var x = 9; // declaration & assignment 17 | var fun = function() {...}; // var decl., assignmt, and func. defin. 18 | alert("hi"); // function call 19 | 20 | // Avoid 21 | // NO semicolons after }: 22 | if (...) {...} else {...} 23 | for (...) {...} 24 | while (...) {...} 25 | 26 | // BUT: 27 | do {...} while (...); 28 | 29 | // function statement: 30 | function (arg) { /*do this*/ } // NO semicolon after } 31 | 32 | // Exception: 33 | for (var i=0; i < 10; i++) {/*actions*/} // correct 34 | for (var i=0; i < 10; i++;) {/*actions*/} // SyntaxError 35 | -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_03/L0301.js: -------------------------------------------------------------------------------- 1 | // 2 | // L03S01 - Simple variables & good/bad variable names 3 | // 4 | var name = 'Chuck'; // Simple string variable 5 | var i = 0; // Simple integer variable 6 | var answer = true; // Simple boolean variable 7 | 8 | // Naming 9 | var c = "http://www.amazon.com"; // Not ideal 10 | var case = 'CASE0010001'; // Reserved word! 11 | var lastEntryInTheListWithRelatedRecords = true; // a bit long? 12 | // personCount // Indicates a counter/integer 13 | // personList // Must be a list 14 | // personObj // Object 15 | // personGr // GlideRecord -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_04/L04S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L04S01 - Mathematical operators 3 | // 4 | 5 | // Assignment 6 | var a = 12; 7 | var b = 3; 8 | 9 | // Addition 10 | gs.info(2 + 2); 11 | gs.info(a + 2); 12 | b = b + 2; 13 | // b += 2; // shorthand for the line above 14 | gs.info(a + b); 15 | 16 | // Increment by 1 17 | a++; 18 | gs.info(a); 19 | 20 | // Decrement by 1 21 | b--; 22 | gs.info(b); 23 | 24 | // Multiply 25 | gs.info(a * b); 26 | 27 | // Division 28 | gs.info(a / b); 29 | 30 | // Modulo - get the remainder of a division 31 | gs.info(''); 32 | gs.info(a); 33 | gs.info(b); 34 | gs.info(a % b); 35 | 36 | var c = (5 + 4) * 2; 37 | gs.info(c); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_05/L05S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L05S01 - Common error messages 3 | // 4 | gs.info(myUnknownVariable); 5 | ga.info('Hello, world!); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_06/L06S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L06S01 - Strings 3 | // 4 | var firstName = "Chuck"; 5 | var lastName = 'Tomasi'; // Either is ok 6 | var myCar = "Chuck's Car"; // Mix them to avoid issues 7 | 8 | // Note the use of + when strings are involved 9 | var name = firstName + ' ' + lastName; 10 | gs.info(name); 11 | gs.info('length of name=' + name.length); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_07/L07S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L07S01 - Special characters 3 | // 4 | // \n = new line 5 | // \t = tab 6 | // \\ = backslash 7 | // \' = single quote 8 | // \" = double quote 9 | // 10 | gs.info('Single string\nTwo lines'); 11 | gs.info('Chuck\'s simple script'); 12 | gs.info('Don\'t confuse a forward slash (/) with a backslash(\\)'); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_08/L0801.js: -------------------------------------------------------------------------------- 1 | // 2 | // L08S01 - Changing and detecting variable types 3 | // 4 | var i = 5; 5 | var iStr = i.toString(); 6 | gs.info(typeof i); 7 | gs.info(typeof iStr); 8 | 9 | var n = parseInt(iStr); 10 | gs.info(typeof n + ' n=' + n); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_09/L09S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L09S01 - Commenting 3 | // 4 | 5 | // This is a single line comment 6 | 7 | /* This is another way to comment */ 8 | 9 | /* 10 | This is a multi-line comment. 11 | This code is commented out! 12 | var name = 'Chuck'; 13 | */ 14 | gs.info('name = ' + name); 15 | -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_10/L10S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L10S01 - Arithmetic Operators 3 | // 4 | var a = 0; 5 | var b = 1; 6 | gs.info(a < b); 7 | 8 | var n = '3'; 9 | var i = 3; 10 | gs.info(n == i); // REALLY?!! 11 | gs.info(i = 4); // WATCH OUT!!! -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_11/L11S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // S11S01 - If Statements 3 | // 4 | var a = 1; 5 | var b = 3; 6 | var c = 5; 7 | if (a < b) 8 | gs.info('a is less than b'); 9 | 10 | // else 11 | if (a < b) 12 | gs.info('a is less than b'); 13 | else 14 | gs.info('a is greater than or equal to b'); 15 | 16 | // Else if and else 17 | if (a < b) 18 | gs.info('a is less than b'); 19 | else if (a > b) 20 | gs.info('a is greater than b'); 21 | else if (a == b) 22 | gs.info('a equals b'); 23 | else 24 | gs.info('Uh-oh'); 25 | 26 | if (a < b) 27 | if (b < c) 28 | gs.info('a b c are in order'); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_11/L11S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // S11S02 - Boolean logic 3 | // 4 | // AND (&&) - both must be true 5 | // +---------+---------+---------+ 6 | // | AND | true | false | 7 | // +---------+---------+---------+ 8 | // | true | true | false | 9 | // +---------+---------+---------+ 10 | // | false | false | false | 11 | // +---------+---------+---------+ 12 | // 13 | // OR (||) - Either must be true 14 | // +---------+---------+---------+ 15 | // | OR | true | false | 16 | // +---------+---------+---------+ 17 | // | true | true | true | 18 | // +---------+---------+---------+ 19 | // | false | true | false | 20 | // +---------+---------+---------+ 21 | // 22 | // NOT (!) - reverse the logic 23 | // +---------+---------+---------+ 24 | // | NOT | true | false | 25 | // +---------+---------+---------+ 26 | // | | false | true | 27 | // +---------+---------+---------+ 28 | // 29 | var a = 1; 30 | var b = 3; 31 | var c = 5; 32 | 33 | if (a < b && b < c) 34 | gs.info('a b c are in order'); 35 | 36 | if (b > a || b > c) 37 | gs.info('b is greater than one of them.'); 38 | 39 | // Note, indentation can be deceptive!!! 40 | if (a < b) 41 | if (b < c) { 42 | gs.info('a b c are in order'); 43 | gs.info(' that means a is less than c'); 44 | } 45 | else 46 | gs.info('a is greater than or equal to b'); 47 | 48 | var valveOpen = true; 49 | if (valveOpen == true) 50 | gs.info('Valve is currently open'); 51 | 52 | if (bool) 53 | gs.info('Valve is currently open'); 54 | 55 | var valveOpen = false; 56 | if (!valveOpen) 57 | gs.info('Valve is currently closed'); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_12/L12S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L12S01 - The ternary operator 3 | // 4 | // Could have written... 5 | var valveOpen = true; 6 | var openStatusString; 7 | if (valveOpen) 8 | openStatusString = 'open'; 9 | else 10 | openStatusString = 'closed'; 11 | gs.info('1: Valve is currently ' + openStatusString); 12 | 13 | // Introducing a shortcut way... 14 | var openStatusString = (valveOpen) ? 'open' : 'closed'; 15 | gs.info('2: Valve is currently ' + openStatusString); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_13/L13S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L13S01 - Multiple cases 3 | // 4 | // Using if/else if/else if... 5 | var level = 5; 6 | var message = ''; 7 | if (level == 0) 8 | message = 'Empty'; 9 | else if (level == 1 || level == 2) 10 | message = 'Low'; 11 | else if (level == 3) 12 | message = 'Medium'; 13 | else if (level == 4) 14 | message = 'High'; 15 | else if (level == 5) 16 | message = 'Full'; 17 | else 18 | message = 'Uh-oh'; 19 | gs.info('Level=' + level + ' status=' + message); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_13/L13S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L13S02 - Multiple cases 3 | // 4 | // Using the switch statement 5 | var level = 5; 6 | var message = ''; 7 | switch (level) { 8 | case 0: 9 | message = 'Empty'; 10 | break; 11 | 12 | case 1: 13 | case 2: 14 | message = 'Low'; 15 | break; 16 | 17 | case 3: // Warning - what's wrong with case 3? 18 | message = 'Medium'; 19 | case 4: 20 | message = 'High'; 21 | break; 22 | 23 | case 5: 24 | message = 'Full'; 25 | break; 26 | 27 | default: 28 | message = 'Uh-oh!'; 29 | } 30 | gs.info('Level=' + level + ' status=' + message); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_14/L14S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L14S01 - Truthy and Falsy 3 | // 4 | 5 | // Simple case of true and false 6 | // 7 | var boolTrue = true; 8 | var boolFalse = false; 9 | gs.info('boolTrue=' + boolTrue + ' boolFalse=' + boolFalse); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_14/L14S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L14S02 - Truthy and Falsy 3 | // 4 | 5 | // What about numbers 6 | // 7 | var num = 0; // <== try with different numbers 8 | gs.info(num + ' is ' + ((num) ? 'true' : 'false')); 9 | -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_14/L14S03.js: -------------------------------------------------------------------------------- 1 | // 2 | // L14S03 - Truthy and Falsy 3 | // 4 | 5 | // Take a look at strings 6 | // 7 | var string1; 8 | var string2 = null; 9 | var string3 = 'Hello, world!'; 10 | gs.info('string1=' + ((string1) ? 'true' : 'false')); 11 | gs.info('string2=' + ((string2) ? 'true' : 'false')); 12 | gs.info('string3=' + ((string3) ? 'true' : 'false')); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_15/L15S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L15S01 - Simple while loop 3 | // 4 | var i = 0; 5 | while (i < 5) { 6 | gs.info(i); 7 | i++; 8 | } 9 | gs.info('done i=' + i); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_15/L15S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L15S02 - breaking out of a while loop 3 | // 4 | var i = 0; 5 | while (true) { 6 | if (i == 5) 7 | break; 8 | gs.info(i); 9 | ++i; 10 | } 11 | gs.info('done'); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_15/L15S03.js: -------------------------------------------------------------------------------- 1 | // 2 | // L15S03 - Continue - jumping back to the while condition 3 | // 4 | var i = 0; 5 | var done = false; 6 | while (!done) { 7 | if (i < 5) { 8 | ++i; 9 | gs.info(i + ' done=' + done); 10 | continue; 11 | } 12 | gs.info('I think we are done'); 13 | done = true; 14 | } 15 | gs.info(i); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_16/L16S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L16S01 - For loop 3 | // 4 | // Note: break and continue work here too! 5 | for (var i = 0; i < 5; i++) { 6 | gs.info(i); 7 | } 8 | gs.info('done i=' + i); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_17/L17S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L17S01 - do-while 3 | // 4 | var i = 0; 5 | gs.info('start'); 6 | do { 7 | gs.info('i=' + i); 8 | ++i; 9 | } while (i < 5); 10 | gs.info('done i=' + i); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_18/L18S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L18S01 - Nested loops 3 | // 4 | for (var i = 0; i < 5; i++) { 5 | for (var j = 0; j < 3; j++) { 6 | gs.info('i=' + i + ' j=' + j); 7 | } 8 | } 9 | gs.info('Done i=' + i + ' j=' + j); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_19/L19S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L19S01 - Functions 3 | // 4 | function sayHello() { 5 | gs.info('Hello'); 6 | } 7 | sayHello(); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_19/L19S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L19S02 - Function with a parameter 3 | // 4 | function toCelsius(fahrenheit) { 5 | 6 | var c = (5 / 9) * (fahrenheit - 32); 7 | 8 | gs.info(c); 9 | } 10 | toCelsius(32); 11 | toCelsius(100); 12 | -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_19/L19S03.js: -------------------------------------------------------------------------------- 1 | // 2 | // L19S03 - Function with a return value 3 | // 4 | function toCelsius(fahrenheit) { 5 | 6 | return (5 / 9) * (fahrenheit - 32); 7 | 8 | } 9 | var c = toCelsius(32); 10 | gs.info(c); 11 | c = toCelsius(212); 12 | gs.info(c); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_19/L19S04.js: -------------------------------------------------------------------------------- 1 | // 2 | // L19S04 - Local variables scope 3 | // 4 | function toCelsius(fahrenheit) { 5 | 6 | // c is only known in the function toCelsius() 7 | var c = (5 / 9) * (fahrenheit - 32); 8 | 9 | return c; 10 | } 11 | gs.info(c); // What happened? 12 | -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_19/L19S05.js: -------------------------------------------------------------------------------- 1 | // 2 | // L19S05 - Global variables and local 3 | // 4 | var convertTo = 'F'; 5 | 6 | function toCelsius(f) { 7 | 8 | var c = (5 / 9) * (f - 32); 9 | 10 | return c; 11 | } 12 | 13 | function toFahrenheit(c) { 14 | 15 | var f = c * 9 / 5 + 32; 16 | 17 | return f; 18 | } 19 | 20 | function convertTemp(temp) { 21 | 22 | // use the global variable to determine conversion 23 | if (convertTo == 'C') { 24 | return toCelsius(temp); 25 | } else { 26 | return toFahrenheit(temp); 27 | } 28 | } 29 | 30 | gs.info(convertTemp(100)); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_19/L19S06.js: -------------------------------------------------------------------------------- 1 | // 2 | // L19S06 - Self running function 3 | // 4 | 5 | // This code is outside the function 6 | var i = 20; 7 | 8 | (function() { 9 | 10 | // Local variable 11 | i = 10; // uh-oh, forgot the var! 12 | 13 | gs.info('i=' + i); 14 | 15 | }()); 16 | 17 | i = 3; 18 | gs.info('i=' + i); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_20/L20S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L20S01 - bad script w/o try/catch 3 | // 4 | 5 | for (var i = 0; i < 5; i++) { 6 | gs.info('i=' + i + ' answer=' + answer); 7 | } 8 | gs.info('done'); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_20/L20S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L20S02 - Trapping that error 3 | // 4 | try { 5 | for (var i = 0; i < 5; i++) { 6 | gs.info('i=' + i + ' answer=' + answer); 7 | } 8 | } catch (e) { 9 | gs.error('Uh-oh ' + e.message); 10 | } 11 | gs.info('done'); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_20/L20S03.js: -------------------------------------------------------------------------------- 1 | // 2 | // L20S03 - And finally… 3 | // 4 | try { 5 | for (var i = 0; i < 5; i++) { 6 | gs.info('i=' + i + ' answer=' + answer); 7 | } 8 | } catch (e) { 9 | gs.error('Uh-oh ' + e.message); 10 | } finally { 11 | gs.info('done'); 12 | } 13 | -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_21/L21S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L21S01 - Simple Database query 3 | // 4 | 5 | // Get and display numbers on all incidents 6 | var incGr = new GlideRecord('incident'); 7 | incGr.query(); 8 | 9 | while (incGr.next()) { 10 | gs.info(incGr.getValue('number')); 11 | } 12 | -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_21/L21S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L21S02 - Get and display numbers on all incidents v2 3 | // 4 | var incGr = new GlideRecord('incident'); 5 | incGr.addQuery('active', true); 6 | incGr.orderBy('number'); 7 | incGr.setLimit(5); 8 | incGr.query(); 9 | 10 | while (incGr.next()) { 11 | gs.info(incGr.getValue('number')); 12 | } -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_21/L21S03.js: -------------------------------------------------------------------------------- 1 | // 2 | // L21S03 - What is 'number’? 3 | // 4 | var incGr = new GlideRecord('incident'); 5 | incGr.setLimit(1); 6 | incGr.query(); 7 | 8 | if (incGr.next()) { 9 | var dotNumber = incGr.number; 10 | var gvNumber = incGr.getValue('number'); 11 | gs.info('dotNumber=' + typeof dotNumber + ' gvNumber=' + typeof gvNumber); 12 | } 13 | 14 | // Why should I care? I'll show you when we get to arrays... 15 | -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_21/L21S04.js: -------------------------------------------------------------------------------- 1 | // 2 | // L21S04 - getting a single record quickly 3 | // Just need one record? Use .get(SYSID) or .get('fieldName', fieldValue) 4 | // 5 | var incGr = new GlideRecord('incident'); 6 | 7 | if (incGr.get('965c9e5347c12200e0ef563dbb9a7156')) { 8 | gs.info(incGr.getValue('number')); 9 | } 10 | 11 | // or... 12 | var incGr = new GlideRecord('incident'); 13 | 14 | if (incGr.get('number', 'INC0000059')) { 15 | gs.info(incGr.getValue('sys_id')); 16 | } -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_22/L22S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L22S01 - Arrays 3 | // 4 | 5 | // Make a simple array 6 | // 7 | // Optional declaration, but not preferred: 8 | // var list = Array(); 9 | var list = []; 10 | list[0] = 1; 11 | list[1] = 3; 12 | list[2] = 5; 13 | gs.info('length of list is: ' + list.length); 14 | -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_22/L22S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L22S02 - Shorter way 3 | // 4 | var list = [1, 3, 5]; 5 | gs.info('length of list is: ' + list.length); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_22/L22S03.js: -------------------------------------------------------------------------------- 1 | // 2 | // L22S03 - Loops and arrays 3 | // 4 | var list = [1, 3, 5]; 5 | for (var i = 0; i < list.length; i++) { 6 | gs.info('i=' + i + ' value=' + list[i]); 7 | } 8 | 9 | // Slightly better 10 | var list = [1, 3, 5]; 11 | var len = list.length; 12 | for (var i = 0; i < len; i++) { 13 | gs.info('i=' + i + ' value=' + list[i]); 14 | } -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_23/L23S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L23S01 forEach with external function 3 | // 4 | var list = [1, 3, 5]; 5 | 6 | list.forEach(myFunction); 7 | 8 | function myFunction(item) { 9 | gs.info('myFunction item=' + item); 10 | } 11 | -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_23/L23S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L23S02 embedded forEach 3 | // 4 | var list = [1, 3, 5]; 5 | 6 | list.forEach(function (item) { 7 | gs.info('embedded function item=' + item); 8 | }); 9 | -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_23/L23S03.js: -------------------------------------------------------------------------------- 1 | // 2 | // L23S03 - What else can you get.. 3 | // 4 | var list = ['apple', 'banana', 'orange']; 5 | 6 | list.forEach(function (item, index, arr) { 7 | gs.info('embedded function item=' + item + ' index=' + index + ' arr=' + arr); 8 | }); 9 | -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_24/L24S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L24S01 - Common array methods/functions 3 | // 4 | var list = ['Chuck', 'Kreg', 'Stacey']; 5 | gs.info('list=' + list); 6 | -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_24/L24S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L24S02 - join(string) 3 | // 4 | var list = ['Chuck', 'Kreg', 'Stacey']; 5 | gs.info('join: list=' + list.join(', ')); 6 | 7 | // push(value1, value2, ..., valueX) 8 | list.push('Dave'); 9 | list.push('Andrew'); 10 | gs.info('push: list=' + list.join(', ')); 11 | 12 | // pop() 13 | list.pop(); 14 | gs.info('pop: list=' + list.join(', ')); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_24/L24S03.js: -------------------------------------------------------------------------------- 1 | // 2 | // L24S03 - shift() 3 | // 4 | var list = ['Chuck', 'Kreg', 'Stacey']; 5 | gs.info('Before shift(), list[0]=' + list[0]); 6 | list.shift(); 7 | gs.info('shift: list=' + list.join(', ')); 8 | gs.info('After shift(), list[0]=' + list[0]); 9 | -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_24/L24S04.js: -------------------------------------------------------------------------------- 1 | // 2 | // L24S04 - unshift 3 | // 4 | var list = ['Chuck', 'Kreg', 'Stacey']; 5 | var newLength = list.unshift('Jason', 'Andrew'); 6 | gs.info('new length=' + newLength + ' unshift() list=' + list.join(', ')); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_24/L24S05.js: -------------------------------------------------------------------------------- 1 | // 2 | // L24S05 - splice(position, n-remove, value1, value2, ..., valueX) - add/remove elements somewhere in the middle 3 | // 4 | var names = ["Eric", "Donna", "Melanie", "Jessie"]; 5 | gs.info(names.join(', ')); 6 | names.splice(2, 0, "Cary", "Henri"); 7 | gs.info(names.join(', ')); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_24/L24S06.js: -------------------------------------------------------------------------------- 1 | // 2 | // L24S06 - slice(start, end) - extract part of an array in to another array 3 | // 4 | var names = ["Eric", "Donna", "Melanie", "Jessie", "Howard", "Tomasz"]; 5 | gs.info(names.join(', ')); 6 | var subNames = names.slice(1, 3); // Get names at positions 1 and 2 7 | gs.info(subNames.join(', ')); 8 | -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_24/L24S07.js: -------------------------------------------------------------------------------- 1 | // 2 | // L24S08 - Reverse the elements of an array 3 | // 4 | var names = ["Eric", "Donna", "Melanie", "Jessie", "Howard", "Tomasz"]; 5 | names.reverse(); 6 | gs.info(names.join(', ')); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_24/L24S08.js: -------------------------------------------------------------------------------- 1 | // 2 | // L24S09 - Getting the value 3 | // 4 | var list = []; 5 | var incGr = new GlideRecord('incident'); 6 | incGr.addQuery('priority', '1'); 7 | incGr.query(); 8 | 9 | while (incGr.next()) { 10 | list.push(incGr.getValue('sys_id')); 11 | } 12 | 13 | gs.info('list=\n' + list.join('\n')); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_25/L25S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L25S01 - ArrayUtil 3 | // 4 | var au = new ArrayUtil(); 5 | var names = [ 6 | "Eric", 7 | "Donna", 8 | "Melanie", 9 | "Jessie", 10 | "Howard", 11 | "Eric", 12 | "Jessie", 13 | "Tomasz" 14 | ]; 15 | var newNames = au.unique(names); 16 | gs.info(newNames.join(', ')); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_26/L26S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L26S01 - Simple Objects 3 | // 4 | var box = {}; 5 | box.height = 20; 6 | box.width = 10; 7 | box.length = 10; 8 | box.material = "cardboard"; 9 | box.open = true; 10 | gs.info(box.material); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_26/L26S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L26S02 - Bracket notation… 3 | // 4 | var vehicle = {}; 5 | vehicle['year'] = 2018; 6 | vehicle['make'] = "Toyota"; 7 | vehicle['model'] = "Sienna"; 8 | gs.info(vehicle['year'] + ' ' + vehicle['make'] + ' ' + vehicle['model']); 9 | -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_26/L26S03.js: -------------------------------------------------------------------------------- 1 | // 2 | // L26S03 - Shortcut - note the double quotes 3 | // 4 | var vehicle = { 5 | "year" : 2018, 6 | "make" : "Toyota", 7 | "model" : "Sienna" 8 | }; 9 | gs.info(vehicle['year'] + ' ' + vehicle['make'] + ' ' + vehicle['model']); 10 | -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_27/L27S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L27S01 - hasOwnProperty 3 | // 4 | var vehicle = { 5 | "year" : 2018, 6 | "make" : "Toyota", 7 | "model" : "Sienna" 8 | }; 9 | gs.info(vehicle.hasOwnProperty("year")); // <== true 10 | gs.info(vehicle.hasOwnProperty("price")); // <== false -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_28/L28S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L28S01 - Get object keys 3 | // 4 | var vehicle = { 5 | "year" : 2018, 6 | "make" : "Toyota", 7 | "model" : "Sienna" 8 | }; 9 | for (var key in vehicle) { 10 | gs.info('key=' + key + ' value=' + vehicle[key]); 11 | } -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_29/L29S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L29S01 - Array of Objects 3 | // 4 | var bookList = [ 5 | { 6 | "title" : "Harry Potter and the Chamber of Secrets", 7 | "author" : "J.K. Rowling" 8 | }, 9 | { 10 | "title" : "Moby Dick", 11 | "author" : "Herman Melville" 12 | }, 13 | { 14 | "title" : "A Tale of Two Cities", 15 | "author" : "Charles Dickens" 16 | } 17 | ]; 18 | var len = bookList.length; 19 | gs.info('Last author=' + bookList[len].author); 20 | 21 | for (var i = 0; i < len; i++) { 22 | var book = bookList[i]; 23 | gs.info(i + ' - Title: ' + book.title + ' - Author: ' + book.author); 24 | } -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_30/L30S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L30S01 - Stringify and Parse 3 | // 4 | var bookList = [ 5 | { 6 | "title" : "Harry Potter and the Chamber of Secrets", 7 | "author" : "J.K. Rowling" 8 | }, 9 | { 10 | "title" : "Moby Dick", 11 | "author" : "Herman Melville" 12 | }, 13 | { 14 | "title" : "A Tale of Two Cities", 15 | "author" : "Charles Dickens" 16 | } 17 | ]; 18 | gs.info(bookList); // That's not very helpful! 19 | 20 | var bookListStr = JSON.stringify(bookList); 21 | gs.info(bookListStr); // I can read it - sort of 22 | 23 | var bookListStrFormat = JSON.stringify(bookList, null, 4); 24 | gs.info(bookListStrFormat); // Ah - that's better! -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_30/L30S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L30S02 - Parse example 3 | // 4 | var libraryStr = '[{"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"}]'; 5 | gs.info('length=' + libraryStr.length); 6 | var libraryObj = JSON.parse(libraryStr); 7 | gs.info('length=' + libraryObj.length); 8 | gs.info(JSON.stringify(libraryObj, null, 4)); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_31/L31S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L31S01 More string stuff 3 | // Find the position of a character or substring 4 | // 5 | var subject = 'Warning: Email is not working'; 6 | var pos = subject.indexOf('Email'); 7 | gs.info(pos); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_31/L31S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L31S02 - Use the position of a character/substring as a condition 3 | // 4 | var short_description = 'System is displaying error message'; 5 | if (short_description.indexOf('error') >= 0) { 6 | gs.info("Error message found"); 7 | } -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_31/L31S03.js: -------------------------------------------------------------------------------- 1 | // 2 | // L31S03 - Get a substring 3 | // 4 | var str = 'Approved: RITM0010001 - Laptop renewal'; 5 | var pos = str.indexOf('RITM'); 6 | var ritmNumber = str.substring(pos, pos + 11); 7 | gs.info(ritmNumber); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_31/L31S04.js: -------------------------------------------------------------------------------- 1 | // 2 | // L31S04 - Case matters with strings 3 | // 4 | var firstName = 'Chuck'; 5 | var loginName = 'chuck'; 6 | if (loginName == firstName) { 7 | gs.info('names match'); 8 | } else { 9 | gs.info('names do not match'); 10 | } -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_31/L31S05.js: -------------------------------------------------------------------------------- 1 | // 2 | // L31S05 - Using toUpper or toLower for better matching 3 | // 4 | var firstName = 'Chuck'; 5 | var loginName = 'chuck'; 6 | gs.info('firstName=' + firstName.toUpperCase() + ' loginName=' + loginName.toUpperCase()); 7 | if (loginName.toUpperCase() == firstName.toUpperCase()) { 8 | gs.info('names match'); 9 | } else { 10 | gs.info('names do not match'); 11 | } -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_32/L32S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L32S01 - Recursion 3 | // 4 | function factorial(x) { 5 | 6 | // TERMINATION 7 | if (x < 0) 8 | return; 9 | 10 | // BASE 11 | if (x === 0) 12 | return 1; 13 | 14 | // RECURSION 15 | return x * factorial(x - 1); 16 | } 17 | gs.info(factorial(3)); // 6 -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_33/L33S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L33S01 - Classes, Objects, and Prototypes 3 | // 4 | 5 | var person = Class.create(); 6 | person.prototype = { 7 | initialize: function() { 8 | this.firstName = ''; 9 | this.lastName = ''; 10 | }, 11 | 12 | setFirstName : function(str) { 13 | this.firstName = str; 14 | }, 15 | 16 | setLastName : function(str) { 17 | this.lastName = str; 18 | }, 19 | 20 | getDisplayName : function() { 21 | return this.firstName + ' ' + this.lastName; 22 | }, 23 | 24 | type: person 25 | }; 26 | 27 | var me = new person(); 28 | me.setFirstName('Chuck'); 29 | me.setLastName('Tomasi') 30 | gs.info('me=' + me.firstName + ' ' + me.lastName); // Not advised 31 | var name = me.getDisplayName(); 32 | gs.info(name); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_33/L33S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L33S02 - Initialize values 3 | // 4 | var person = Class.create(); 5 | person.prototype = { 6 | initialize: function(str1, str2) { 7 | this.firstName = str1; 8 | this.lastName = str2; 9 | }, 10 | 11 | setFirstName : function(str) { 12 | this.firstName = str; 13 | }, 14 | 15 | setLastName : function(str) { 16 | this.lastName = str; 17 | }, 18 | 19 | getDisplayName : function() { 20 | return this.firstName + ' ' + this.lastName; 21 | }, 22 | 23 | type: 'person' 24 | }; 25 | 26 | var me = new person('Chuck', 'Tomasi'); 27 | var name = me.getDisplayName(); 28 | gs.info(name); 29 | me.setFirstName('Fred'); 30 | me.setLastName('Luddy'); 31 | gs.info(me.getDisplayName()); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_34/L34S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L34S01 - Passing objects to functions 3 | // 4 | var item = Class.create(); 5 | item.prototype = { 6 | initialize: function() { 7 | }, 8 | 9 | debugObject : function(obj) { 10 | 11 | gs.info('object=' + JSON.stringify(obj, null, 4)); 12 | }, 13 | 14 | type: 'item' 15 | }; 16 | 17 | var myObj = { 18 | "type" : "vehicle", 19 | "engine" : true, 20 | "wheels" : 4, 21 | "state" : "allocated" 22 | }; 23 | var myItem = new item(); 24 | myItem.debugObject(myObj); // Loosely coupled -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_35/L35S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L35S01 - Inheritance 3 | // 4 | var vehicle = Class.create(); 5 | vehicle.prototype = { 6 | initialize: function(year, make, model) { 7 | this.make = make; 8 | this.model = model; 9 | this.year = year; 10 | }, 11 | 12 | register : function() { 13 | gs.info(this.getDisplayName() + ' registered!'); 14 | }, 15 | 16 | info : function() { 17 | gs.info('Vehicle info: TBD'); 18 | }, 19 | 20 | getDisplayName : function() { 21 | 22 | return this.year + ' ' + this.make + ' ' + this.model; 23 | 24 | }, 25 | 26 | type: 'vehicle' 27 | }; 28 | 29 | var car = Class.create(); 30 | car.prototype = Object.extendsObject(vehicle, { 31 | 32 | findDealer : function() { 33 | gs.info('Find dealer is not yet implemented'); 34 | }, 35 | 36 | info : function() { 37 | gs.info('Car info: TBD'); 38 | }, 39 | 40 | type: 'car' 41 | }); 42 | 43 | var v1 = new vehicle('2018', 'John Deere', 'Tractor'); 44 | v1.register(); 45 | v1.info(); 46 | 47 | var v2 = new car('2017', 'Honda', 'CR-V'); 48 | v2.register(); 49 | v2.findDealer(); 50 | v2.info(); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_36/L36S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L36S01 - Simple scripted REST API (GET) resource 3 | // 4 | (function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) { 5 | 6 | return "hello, world!"; 7 | 8 | })(request, response); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_36/L36S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L36S02 - Scripted REST API with query parameters 3 | // 4 | (function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) { 5 | 6 | // Example Query parameters 7 | // https://?active=true&name=now 8 | var queryParams = request.queryParams; 9 | var isActiveQuery = queryParams.active; //true 10 | var nameQueryVal = queryParams.name; //‘now’ 11 | 12 | var answer = "Response: active=" + isActiveQuery + " name=" + nameQueryVal; 13 | 14 | return answer; 15 | 16 | })(request, response); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_36/L36S03.js: -------------------------------------------------------------------------------- 1 | // 2 | // L36S03 - Scripted REST API with path parameters 3 | // 4 | (function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) { 5 | 6 | // Example path parameters 7 | // https://instance.service-now.com/api/now/myservice/{tableName}/{id} 8 | // https://instance.service-now.com/api/now/myservice/myApp_table/1234 9 | var pathParams = request.pathParams; 10 | var tableName = pathParams.tableName; //‘myApp_table’ 11 | var id = pathParams.id; //‘1234’ 12 | 13 | var answer = "Response: tableName=" + tableName + " id=" + id; 14 | 15 | return answer; 16 | 17 | })(request, response); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_36/L36S04.js: -------------------------------------------------------------------------------- 1 | // 2 | // L36S04 - Scripted REST API (POST) with request body payload 3 | // 4 | (function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) { 5 | 6 | var name = request.body.data.name; 7 | var id = request.body.data.id; 8 | var color = request.body.data.color; 9 | 10 | var answer = "Response: name=" + name + " id=" + id + " color=" + color; 11 | 12 | return answer; 13 | 14 | })(request, response); -------------------------------------------------------------------------------- /Section 1 - Learn JavaScript on the Now Platform with Chuck Tomasi/Lesson_36/L36S05.js: -------------------------------------------------------------------------------- 1 | // 2 | // L36S05 - Scripted REST API with POST and response 3 | // 4 | (function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) { 5 | 6 | var name = request.body.data.name; 7 | var id = request.body.data.id; 8 | var color = request.body.data.color; 9 | 10 | // Do some processing here 11 | 12 | var answer = {}; 13 | answer.status = "OK"; 14 | answer.author = "system"; 15 | answer.item = {"name" : "Rome", "owner" : "Chuck Tomasi", "count" : 12}; 16 | answer.active = true; 17 | response.setBody(answer); 18 | 19 | return response; 20 | 21 | })(request, response); -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_01/L01S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L01S01 - Review of our other looping methods 3 | // 4 | 5 | // Start by declaring an array with some elements. 6 | var fruits = ['Apple', 'Banana', 'Cherry']; 7 | 8 | // for loop 9 | for (var i = 0; i < fruits.length; i++){ 10 | gs.info('for loop: At index ' + i + ' we have ' + fruits[i]); 11 | } 12 | 13 | // forEach loop 14 | fruits.forEach(function (item, index) { 15 | gs.info('forEach loop: At index ' + index + ' we have ' + item); 16 | }); 17 | -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_01/L01S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L01S02 - The for...in loop 3 | // 4 | 5 | // Start by declaring an array with some elements. 6 | var fruits = ['Apple', 'Banana', 'Cherry']; 7 | 8 | // for...in loop 9 | for (var index in fruits) { 10 | // Notice, we get the index, not the value. 11 | gs.info('for in...loop: At index ' + index + ' we have: ' + fruits[index]); 12 | } 13 | -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_01/L01S03.js: -------------------------------------------------------------------------------- 1 | // 2 | // L01S03 - A slight difference between this method and the others 3 | // 4 | 5 | // Start by declaring a couple of arrays with some elements. But add a custom property to each array 6 | var fruits = ['Apple', 'Banana', 'Cherry']; 7 | fruits.customProperty = 'Not_in_array' 8 | 9 | var vegetables = ['Avocado', 'Broccoli', 'Carrot']; 10 | vegetables.customProperty = 'Not_in_array' 11 | 12 | // for loop 13 | for (var i = 0; i < fruits.length; i++){ 14 | gs.info('At index ' + i + ' we have ' + fruits[i]); 15 | } 16 | 17 | // for...in loop 18 | for (var index in vegetables) { 19 | gs.info('At index ' + index + ' we have: ' + vegetables[index]); // the customProperty appears! 20 | } 21 | -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_01/Lesson_01_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Create an array of 4 strings, and then set a custom property for that array. The goal is to have it display each string on separate line using a loop. Run a `forEach` loop on that array, a three expressions `for` loop on the same array, and then a `for...in` loop on that array to make sure you see the key difference. What is the difference on the last loop syntax? Let me know in the comments which way you prefer now that you know three different ways to do it. 3 | */ 4 | 5 | // Solution 6 | 7 | var advocates = ['Chuck', 'Earl', 'Lauren', `Pranav`]; 8 | vegetables.title = 'Developer Advocates' 9 | 10 | advocates.forEach(function (item, index) { 11 | gs.info(index + '. ' + item); 12 | }) 13 | 14 | for (var i = 0; i < advocates.length; i++){ 15 | gs.info(i + '. ' + advocates[i]) 16 | } 17 | 18 | for (var i in advocates){ 19 | gs.info(i + '. ' + advocates[i]); 20 | } 21 | 22 | // The difference is that the `for...in` loop also displays the custom preoprty, but the other two loops do not. -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_02/L02S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L02S01 - this example 3 | // 4 | 5 | // Let's start with a simple object with a method. 6 | var myObject = { 7 | value: 'Hello, ServiceNow!', 8 | showValue: function () { 9 | gs.info(this.value); 10 | } 11 | }; 12 | 13 | // Calling the method on the object. 14 | myObject.showValue(); // Outputs: 'Hello, ServiceNow!' 15 | -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_02/L02S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L02S01 - calling this when it's no longer in the function's context 3 | // 4 | 5 | var myObject = { 6 | value: 'Hello, ServiceNow!', 7 | showValue: function () { 8 | gs.info(this.value); 9 | } 10 | }; 11 | 12 | // Assign the function to a variable. 13 | var outsideFunction = myObject.showValue; 14 | 15 | // Now call it without an object context. 16 | outsideFunction(); // Outputs: undefined 17 | -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_02/Lesson_02_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Create a script in which you define an object named userProfile with properties name and logName. Include a method logName that logs the user's name using this. Then, outside the object, invoke this method in a different context to see how this changes. 3 | 4 | Hints: 5 | Define userProfile with a name property and a logName method. 6 | Use call or apply to change the context of this when calling logName. 7 | */ 8 | 9 | // Solution 10 | 11 | var userProfile = { 12 | name: 'John Doe', 13 | logName: function () { 14 | gs.info('User name is: ' + this.name); 15 | } 16 | }; 17 | 18 | userProfile.logName(); // Correct context, logs 'John Doe' 19 | 20 | // Bonus! Use call or apply to change the context of this when calling logName. 21 | 22 | var anotherProfile = { 23 | name: 'Jane Smith' 24 | }; 25 | userProfile.logName.call(anotherProfile); // Changed context, logs 'Jane Smith' -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_03/L03S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L03S01 - More on scope 3 | // 4 | 5 | // We'll start with a global variable. 6 | var globalVar = 'I am global'; 7 | 8 | function checkScope() { 9 | // This is a local variable, inside a function. 10 | var localVar = 'I am local'; 11 | 12 | // Let's print them out. 13 | gs.info(globalVar); // Outputs: 'I am global' 14 | gs.info(localVar); // Outputs: 'I am local' 15 | } 16 | 17 | checkScope(); 18 | 19 | // Let's see if we can access localVar outside the function. 20 | gs.info(globalVar); // Outputs: 'I am global' 21 | gs.info(localVar); // Throws an error: localVar is not defined. 22 | -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_04/L04S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L04S01 - Hoisting 3 | // 4 | 5 | // Attempting to use a function before it's written. 6 | hoistedFunction(); // Outputs: 'I am hoisted!' 7 | 8 | function hoistedFunction() { 9 | gs.info('I am hoisted!'); 10 | } 11 | 12 | // Now, let's try the same with a variable. 13 | gs.info(hoistedVar); // Outputs: undefined 14 | var hoistedVar = 'I exist!'; 15 | -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_04/Lesson_04_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | I want you to demonstrate the concept of hoisting in JavaScript. Create two functions, one declared using a function declaration and the other with a function expression. Attempt to invoke both before their declaration and observe the results. 3 | 4 | Hints: 5 | Use function declaration for one function and function expression (assigned to a variable) for the other. 6 | Call these functions before their respective definitions in the script. 7 | */ 8 | 9 | // Solution 10 | 11 | declaredFunction(); // Works due to hoisting 12 | expressedFunction(); // TypeError: expressedFunction is not a function 13 | 14 | function declaredFunction() { 15 | gs.info('This is a function declaration.'); 16 | } 17 | 18 | var expressedFunction = function() { 19 | gs.info('This is a function expression.'); 20 | }; 21 | -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_05/L05S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L05S01 - Date and time 3 | // 4 | 5 | // Let's create a new Date object and see what we get. 6 | var now = new Date(); 7 | gs.info('Current date and time: ' + now); 8 | 9 | // How about getting specific parts of the date? 10 | gs.info('The year is: ' + now.getFullYear()); 11 | gs.info('The month is: ' + (now.getMonth() + 1)); // Remember, months are zero-indexed! 12 | gs.info('The day is: ' + now.getDate()); 13 | 14 | // You can also set specific parts of the date. 15 | now.setFullYear(2020); 16 | gs.info('Changed year: ' + now.getFullYear()); 17 | 18 | // And format dates into readable strings. 19 | gs.info('Locale date string: ' + now.toLocaleDateString()); 20 | -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_05/Lesson_05_Exercise.js: -------------------------------------------------------------------------------- 1 | // Part 1 2 | // Imagine that we want to know the date would it be if it was 30 days after today's date. 3 | // What is wrong with the following code? 4 | 5 | var now = new Date(); 6 | var later = now.getDate() + 30; 7 | gs.info(later); 8 | 9 | // Solution: We only get one number back and if it's more than 31 (the longest month is only 31 days) it doesn't restart back to 1 10 | 11 | // Part 2 12 | // To find the date 30 days after today, how would you edit the below code to display the date as if it was 30 days after today's date? 13 | 14 | var now = new Date(); 15 | var later = now.setDate(now.getDate()); 16 | gs.info(new Date(later)); 17 | 18 | // Solution 19 | 20 | var now = new Date(); 21 | var later = now.setDate(now.getDate() + 30); 22 | gs.info(new Date(later)); -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_06/L06S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L06S01 - Simple Pattern Matching 3 | // 4 | 5 | // Starting with something straightforward, let's match a word in a string. 6 | var wordPattern = /magic/; 7 | 8 | // Check if the word "magic" is in our test string. 9 | var testString = 'The magic of RegEx starts here.'; 10 | gs.info('Does the word match? ' + wordPattern.test(testString)); 11 | 12 | // Output: Does the word match? true 13 | -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_06/L06S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L06S02 - Using special characters 3 | // 4 | 5 | // Now, let's use special characters to match any one-digit number. 6 | var digitPattern = /\d/; 7 | 8 | // Let's test this pattern against a string containing numbers. 9 | var stringWithNumbers = 'ServiceNow 2023'; 10 | gs.info('Is there a digit? ' + digitPattern.test(stringWithNumbers)); 11 | 12 | // Output: Is there a digit? true 13 | -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_06/L06S03.js: -------------------------------------------------------------------------------- 1 | // 2 | // L06S03 - Pattern matching with quantifiers 3 | // 4 | 5 | // Moving on, let's match a series of digits using quantifiers. 6 | var multipleDigitsPattern = /\d{4}/; 7 | 8 | // We'll see if we can match a four-digit year in a string. 9 | var yearString = 'The year is 2023.'; 10 | gs.info('Does the year match? ' + multipleDigitsPattern.test(yearString)); 11 | 12 | // Output: Does the year match? true 13 | -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_06/L06S04.js: -------------------------------------------------------------------------------- 1 | // 2 | // L06S04 - getting complex 3 | // 4 | 5 | // Let's start with creating a simple RegEx to match email addresses. 6 | var emailPattern = /\S+@\S+\.\S+/; 7 | 8 | // Now, we'll test this pattern against a string. 9 | var testEmail = 'hello@example.com'; 10 | gs.info('Does the email match? ' + emailPattern.test(testEmail)); 11 | 12 | // Let's see what happens when we try a pattern match on a non-email string. 13 | var notEmail = 'hello@examplecom'; 14 | gs.info('Does the non-email match? ' + emailPattern.test(notEmail)); 15 | -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_06/L06S05.js: -------------------------------------------------------------------------------- 1 | // 2 | // L06S01 - Using .replace 3 | // 4 | 5 | // Let's demonstrate replacing text in a string using a RegEx pattern. 6 | var replacePattern = /SN/g; 7 | 8 | // We'll replace 'SN' with 'ServiceNow' in our test string. 9 | var replaceString = 'SN is awesome. SN rocks!'; 10 | var newString = replaceString.replace(replacePattern, 'ServiceNow'); 11 | gs.info('Replaced string: ' + newString); 12 | 13 | // Output: Replaced string: SN is awesome. SN rocks! 14 | -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_06/Lesson_06_Exercise.js: -------------------------------------------------------------------------------- 1 | // Your exercise is to create a Regular Expression to match a phone number in the format (123) 456-7890. Test your RegEx with different strings to see if it accurately identifies phone numbers. 2 | // Hints: 3 | // \d to find digits 4 | // Don't forget to "escape" certain characters 5 | // a{5} is how you would say "exactly five a's" 6 | 7 | // Solution 8 | var wordPattern = /\(\d{3}\) \d{3}-\d{4}/; 9 | var testString = '(123) 456-7890'; 10 | gs.info('Does it match? ' + wordPattern.test(testString)); -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_07/L07S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L07S01 - Namespace patterns 3 | // Read: https://codecreative.io/blog/interface-design-patterns-for-script-includes/ 4 | // 5 | 6 | var MyServiceNowApp = { 7 | doSomething: function() { 8 | // Put function code here 9 | }, 10 | 11 | doSomethingElse: function() { 12 | // Put other function code here 13 | } 14 | }; 15 | 16 | MyServiceNowApp.doSomething(); 17 | MyServiceNowApp.doSomethingElse(); -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_07/Lesson_07_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Create a namespace for a mock ServiceNow application. The namespace should include a version property, an init function, and a sub-namespace for utilities with a couple of utility functions. Demonstrate calling one of the utility functions from the namespace. 3 | 4 | Hints: 5 | Define a global object for your namespace. 6 | Include nested objects and functions within this namespace. 7 | Access the functions using the namespace. 8 | */ 9 | 10 | // Solution 11 | 12 | var MySNApp = { 13 | version: '1.0', 14 | init: function () { 15 | gs.info('Initializing MySNApp version ' + this.version); 16 | }, 17 | utils: { 18 | log: function (message) { 19 | gs.info('MySNApp log: ' + message); 20 | }, 21 | calculate: function (a, b) { 22 | return a + b; 23 | } 24 | } 25 | }; 26 | 27 | MySNApp.init(); 28 | MySNApp.utils.log('Hello, ServiceNow'); -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_08/L0801.js: -------------------------------------------------------------------------------- 1 | // 2 | // L08S01 - User information 3 | // 4 | 5 | // Let's find out who's the current user. 6 | var currentUser = gs.getUser(); 7 | gs.info('Current User ID: ' + currentUser.getID()); 8 | gs.info('Current User Roles: ' + currentUser.getRoles()); 9 | gs.info('Current User Name: ' + gs.getUserName()); -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_08/L0802.js: -------------------------------------------------------------------------------- 1 | // 2 | // L08S02 - Instance information 3 | // 4 | 5 | // Now, let's find out some information about our instance 6 | gs.info('This instance name is ' + gs.getProperty('instance_name')); 7 | gs.info('The URL for this instance is ' + gs.getProperty('glide.servlet.uri')); -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_08/L0803.js: -------------------------------------------------------------------------------- 1 | // 2 | // L08S03 - Miscellaneous methods 3 | // 4 | 5 | // GlideSystem also provides utility methods. 6 | 7 | gs.info(gs.beginningOfLastWeek()); 8 | gs.info(gs.beginningOfNextMonth()); 9 | 10 | gs.info(gs.isLoggedIn()); -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_09/L09S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L09S01 - Counting records 3 | // 4 | 5 | // Remembering how we do it in GlideRecord 6 | 7 | var incidentGR = new GlideRecord('incident'); 8 | incidentGR.addQuery('priority', '1'); 9 | incidentGR.query(); 10 | 11 | gs.info('Count of High Priority Incidents: ' + incidentGR.getRowCount()); 12 | 13 | // Let's count the number of incidents with high priority with GlideAggregate instead 14 | var incidentGA = new GlideAggregate('incident'); 15 | incidentGA.addAggregate('COUNT'); 16 | incidentGA.addQuery('priority', '1'); // Filtering for high priority incidents. 17 | incidentGA.query(); 18 | 19 | if (incidentGA.next()) { 20 | gs.info('Count of High Priority Incidents: ' + incidentGA.getAggregate('COUNT')); 21 | } 22 | -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_09/L09S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L09S02 - Summing values 3 | // 4 | 5 | // Now, let's calculate the total downtime from all outage records. 6 | var incidentGA = new GlideAggregate('incident'); 7 | incidentGA.addQuery('reassignment_count','!=','0'); 8 | incidentGA.addAggregate('SUM', 'reassignment_count'); 9 | incidentGA.query(); 10 | 11 | if (incidentGA.next()) { 12 | gs.info('Total reassignments on incidents: ' + incidentGA.getAggregate('SUM', 'reassignment_count')); 13 | } -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_09/L09S03.js: -------------------------------------------------------------------------------- 1 | // 2 | // L09S03 - Grouping results 3 | // 4 | 5 | // How about grouping the number of incidents by category? 6 | var incidentGA = new GlideAggregate('incident'); 7 | incidentGA.addAggregate('COUNT'); 8 | incidentGA.groupBy('category'); 9 | incidentGA.query(); 10 | 11 | while (incidentGA.next()) { 12 | gs.info('Category: ' + incidentGA.category + ' - Count: ' + incidentGA.getAggregate('COUNT')); 13 | } 14 | -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_09/Lesson_09_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Use GlideAggregate to calculate the average priority of incidents for every assignment group 3 | 4 | Hints: 5 | Target the 'incident' table 6 | Use the addAggregate method with 'AVG' and the field 'priority'. 7 | Use the groupBy method with 'assignment_group' 8 | agg.getDisplayValue('assignment_group') will display the name of the group 9 | */ 10 | 11 | // Solution 12 | 13 | var agg = new GlideAggregate('incident'); 14 | agg.groupBy('assignment_group'); 15 | agg.addAggregate('AVG', 'priority'); 16 | agg.query(); 17 | 18 | while (agg.next()) { 19 | gs.info('Average priority for ' + agg.getDisplayValue('assignment_group') + ': ' + agg.getAggregate('AVG', 'priority')); 20 | } 21 | -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_10/L10S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L10S01 - Creating and Manipulating Dates 3 | // 4 | 5 | // Let's create a GlideDateTime object for the current time. 6 | var gdtNow = new GlideDateTime(); 7 | 8 | // Add five days to the current date. 9 | gdtNow.addDaysLocalTime(5); 10 | gs.info('Date in 5 days: ' + gdtNow.getLocalDate().getByFormat('yyyy-MM-dd')); 11 | 12 | // Subtract 30 minutes from the current time. 13 | gdtNow.add(-1800000); 14 | gs.info('Time 30 minutes ago: ' + gdtNow.getLocalTime().getByFormat('HH:mm:ss')); 15 | -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_10/L10S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L10S01 - Comparing dates 3 | // 4 | 5 | // Compare two dates to see which is later. 6 | var gdtStart = new GlideDateTime('2023-01-01T08:30:00'); 7 | var gdtEnd = new GlideDateTime('2023-01-01T09:45:00'); 8 | 9 | if (gdtStart.before(gdtEnd)) { 10 | gs.info('Start time is before end time.'); 11 | } 12 | -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_10/L10S03.js: -------------------------------------------------------------------------------- 1 | // 2 | // L10S01 - Time zone conversions 3 | // 4 | 5 | // Convert a time to another time zone. 6 | var gdtEST = new GlideDateTime(); 7 | gdtEST.setValue('2023-01-01T12:00:00'); // Assume this is UTC time. 8 | gdtEST.convertTimeZone('UTC', 'America/New_York'); 9 | gs.info('Time in EST: ' + gdtEST.getDisplayValue()); 10 | -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_11/L11S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L11S01 - User information 3 | // 4 | 5 | // Obtain an instance of the current user. 6 | var user = gs.getUser(); 7 | 8 | // Display some basic information. 9 | gs.info('Display Name: ' + user.getDisplayName()); 10 | gs.info('First Name: ' + user.getFirstName()); 11 | gs.info('Last Name: ' + user.getLastName()); 12 | gs.info('Username: ' + user.getName()); 13 | gs.info('User ID: ' + user.getID()); 14 | 15 | gs.info('Has ITIL Role: ' + user.hasRole('itil')); 16 | gs.info('Company ID: ' + user.getCompanyID()); 17 | gs.info('Email: ' + user.getEmail()); 18 | gs.info('My group IDs: ' + user.getMyGroups()); 19 | gs.info('My roles: ' + user.getRoles()); 20 | gs.info('My explicitly assigned roles: ' + user.getUserRoles()); 21 | gs.info('Is in Help Desk group: ' + user.isMemberOf('Help Desk')); -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_11/Lesson_11_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Create a script that checks if the current user has a specific role (e.g., 'admin') and logs a message accordingly. 3 | 4 | Hints: 5 | Use gs.getUser() to get the current user. 6 | Utilize hasRole method to check for a specific role. 7 | */ 8 | 9 | // Solution 10 | 11 | var currentUser = gs.getUser(); 12 | if (currentUser.hasRole('admin')) { 13 | gs.info('Current user is an admin.'); 14 | } else { 15 | gs.info('Current user is not an admin.'); 16 | } 17 | 18 | // Just note that hasRole returns true always if this script runs for an admin user! -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_12/L12S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L12S01 - Setting up the client side 3 | // 4 | 5 | // Client-side script to call a server-side script include named 'MyServerCode'. 6 | var ga = new GlideAjax('MyServerCode'); 7 | ga.addParam('sysparm_name', 'getServerTime'); 8 | ga.getXML(handleResponse); 9 | 10 | function handleResponse(response) { 11 | var serverTime = response.responseXML.documentElement.getAttribute("answer"); 12 | alert("Server time is: " + serverTime); 13 | } 14 | -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_12/L12S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L12S02 - Setting up the server side 3 | // 4 | 5 | // Server-side Script Include that corresponds to the client call. 6 | var MyServerCode = Class.create(); 7 | MyServerCode.prototype = Object.extendsObject(AbstractAjaxProcessor, { 8 | 9 | getServerTime: function() { 10 | return new GlideDateTime().getDisplayValue(); 11 | }, 12 | 13 | type: 'MyServerCode' 14 | }); -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_13/L13S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L13S01 - Manipulating field values 3 | // 4 | 5 | // Set the value of a field. 6 | g_form.setValue('short_description', 'This is a dynamic description'); 7 | 8 | // Get the value from a field. 9 | var urgency = 'The urgency is ' + g_form.getValue('urgency'); 10 | g_form.setValue('short_description', urgency); 11 | 12 | // Combining into one so that you don't lose the original short_description 13 | g_form.setValue('short_description', g_form.getValue('short_description') + urgency); -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_13/L13S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L13S02 - Field attributes 3 | // 4 | 5 | // Make a field read-only. 6 | g_form.setReadOnly('assignment_group', true); 7 | 8 | // Hide a field. 9 | g_form.setDisplay('impact', false); 10 | -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_14/L14S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L14S01 - Basic GlideQuery Usage 3 | // 4 | 5 | // Use GlideQuery to retrieve active incidents with high priority. 6 | new GlideQuery('incident') 7 | .where ('active', true) 8 | .where ('priority', 1) 9 | .select('number', 'short_description') 10 | .forEach(function (incident) { 11 | gs.info('Incident ' + incident.number + ': ' + incident.short_description); 12 | }); -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_14/L14S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L14S02 - GlideQuery with conditions and sorting 3 | // 4 | 5 | // Fetching incidents and sorting by creation date. 6 | new GlideQuery('incident') 7 | .where('active', true) 8 | .where('priority', '>', 2) 9 | .orderBy('sys_created_on') 10 | .limit(10) 11 | .select('number', 'sys_created_on') 12 | .forEach(function (incident) { 13 | gs.info('Incident ' + incident.number + ' created on: ' + incident.sys_created_on); 14 | }) -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_14/L14S03.js: -------------------------------------------------------------------------------- 1 | // 2 | // L14S03 - More GlideQuery operations 3 | // 4 | 5 | // Using GlideQuery to update records. 6 | var update = new global.GlideQuery('sys_user') 7 | .where('active', false) 8 | .where('last_name', 'Griffey') 9 | .updateMultiple({ active: true }); 10 | 11 | // Using GlideQuery to insert new records. 12 | var fred = new global.GlideQuery('sys_user') 13 | .insert({ first_name: 'Fred', last_name: 'Luddy' }) 14 | .get(); -------------------------------------------------------------------------------- /Section 2 - Learn MORE JavaScript on the ServiceNow Platform with Earl Duque/Lesson_14/Lesson_14_exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Utilize GlideQuery to retrieve all incidents with no assignment group and log their numbers. 3 | 4 | Hints: 5 | 6 | Use GlideQuery on the 'incident' table. 7 | Apply .where to filter incidents by assignment_group. 8 | Use NULL as your "is empty". 9 | Iterate over the results with .forEach. 10 | */ 11 | 12 | // Solution 13 | 14 | new GlideQuery('incident') 15 | .where('assignment_group', 'NULL') 16 | .select('number') 17 | .forEach(function (incident) { 18 | gs.info('No assignment group: ' + incident.number); 19 | }); -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_01/L01S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L01S01 - let 3 | // 4 | 5 | // Using let for block-level scoping. 6 | if (true) { 7 | let blockScopedVariable = 'I am confined to this block!'; 8 | gs.info(blockScopedVariable); // Works fine here. 9 | } 10 | gs.info(blockScopedVariable); // ReferenceError: blockScopedVariable is not defined. -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_01/L01S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L01S02 - const 3 | // 4 | 5 | // Constants are block-scoped, much like variables defined using let. 6 | const pi = 3.14159; 7 | pi = 3.14; // TypeError: Assignment to constant variable. 8 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_01/L01S03.js: -------------------------------------------------------------------------------- 1 | // 2 | // L01S03 - let vs. const 3 | // 4 | 5 | // Use const by default, only use let if rebinding is needed. 6 | const greeting = 'Hello, ServiceNow!'; 7 | let counter = 0; 8 | 9 | function incrementCounter() { 10 | counter += 1; // 'let' allows us to rebind the counter variable. 11 | } 12 | 13 | // When to use var 14 | // ...don't! -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_02/L02S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L02S01 - The temporal Dead Zone (TDZ) 3 | // 4 | 5 | // Trying to access a var-declared variable before it's defined. 6 | gs.info(beforeVar); //undefined 7 | var beforeVar = 'I\'m on my way!'; 8 | gs.info(beforeVar); 9 | 10 | // Outside of ServiceNow, this is supposed to be an error 11 | gs.info(beforeLet); // ReferenceError: Cannot access 'beforeLet' before initialization 12 | let beforeLet = 'I am in the TDZ until this line!'; 13 | 14 | // The Temporal Dead Zone, as of the making of this lesson, is not supported in ServiceNow, so you shouldn't run into this. But it's important to know in case you encounter this outside of ServiceNow, like if you're scripting in VS Code. -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_03/L03S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L03S01 - Exponentiation operator 3 | // 4 | 5 | // Calculating the square of a number using the exponentiation operator. 6 | let base = 3; 7 | let square = base ** 2; 8 | gs.info('Square: ' + square); 9 | 10 | // Equivalent operation using Math.pow(). 11 | let oldSquare = Math.pow(base, 2); 12 | gs.info('Square (using Math.pow): ' + oldSquare); 13 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_03/L03S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L03S02 - Exponentiation with variables and constants 3 | // 4 | 5 | // Using the exponentiation operator with variables and constants. 6 | const FACTOR = 10; 7 | let exponent = 3; 8 | let result = FACTOR ** exponent; 9 | gs.info('Result: ' + result); 10 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_03/L03S03.js: -------------------------------------------------------------------------------- 1 | // 2 | // L03S03 - Counpound assignment with exponentiation 3 | // 4 | 5 | // The exponentiation operator can be used with compound assignment. 6 | let number = 4; 7 | number **= 2; // Same as number = number ** 2; 8 | gs.info('Number after compound assignment: ' + number); 9 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_04/L04S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L04S01 - ?? vs || Nullish Coalescing Operators 3 | // 4 | 5 | // Suppose we have a function that sets a greeting message. 6 | function setGreeting(message) { 7 | // Using ||, an empty string or zero would be considered falsy and thus replaced by the default. 8 | return message || 'Hello, ServiceNow!'; 9 | } 10 | 11 | // Using the nullish coalescing operator, only null or undefined trigger the default. 12 | function setGreetingNullish(message) { 13 | return message ?? 'Hello, ServiceNow!'; 14 | } 15 | 16 | let greeting1 = setGreeting(''); // Results in 'Hello, ServiceNow!' 17 | let greeting2 = setGreetingNullish(''); // Results in an empty string '' 18 | gs.info(greeting1); 19 | gs.info(greeting2); 20 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_04/L04S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L04S02 - ServiceNow use-case 3 | // 4 | 5 | // Suppose we have a function that sets a greeting message. 6 | function setGreeting() { 7 | let message; // Function returns a null variable 8 | return message; 9 | } 10 | 11 | // In a Script Include or Business Rule, you might get a variable that can be null or undefined. 12 | // The nullish coalescing operator ensures that you have a valid value for further processing. 13 | let userInput = someFunctionThatMayReturnNullOrUndefined(); 14 | let validInput = userInput ?? 'default input'; 15 | 16 | gs.info('User input is: ' + validInput); 17 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_04/L04S03.js: -------------------------------------------------------------------------------- 1 | // 2 | // L04S01 - Usefullness within deep-leveled objects 3 | // 4 | 5 | // Setting up an example 6 | var customer = { 7 | profile: { 8 | comments: 'Great!', 9 | } 10 | }; 11 | 12 | // Imagine accessing a deeply nested property that might not exist. 13 | let customerFeedback = customer.profile.feedback ?? 'No feedback provided'; 14 | 15 | gs.info(customerFeedback); 16 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_05/L05S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L05S01 - Numeric seperators 3 | // 4 | 5 | // Without numeric separators: 6 | let billion = 1000000000; 7 | gs.info(billion); 8 | 9 | // With numeric separators: 10 | let billionReadable = 1_000_000_000; 11 | gs.info(billionReadable); 12 | 13 | // Both output the same value: 14 | // 1000000000 15 | 16 | // Using numeric separators for time constants in milliseconds 17 | const ONE_HOUR = 60 * 60 * 1_000; // One hour in milliseconds 18 | const ONE_DAY = 24 * ONE_HOUR; // One day in milliseconds 19 | gs.info('Milliseconds in one hour: ' + ONE_HOUR); 20 | gs.info('Milliseconds in one day: ' + ONE_DAY); 21 | 22 | // Not allowed: 23 | // 100__000 multiple underscores 24 | // 0_1 leading zeroes 25 | // 100_ trailing underscores 26 | 27 | // Also works with: 28 | // 1_000.000_001 Decimals 29 | // 0b01010110_00111000 Binary 30 | // 0x40_76_38_6A_73 Hexadecimal -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_06/L06S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L06S01 - Logical assignment operator ||= 3 | // 4 | 5 | // Assume we have a function that might return a falsy value. 6 | function getDisplayName() { 7 | // Sometimes, this function might return '', null, or undefined. 8 | return ''; 9 | } 10 | 11 | let displayName = getDisplayName(); 12 | // Using ||= to assign a default value if getDisplayName() is falsy. 13 | displayName ||= 'Default Name'; 14 | gs.info(displayName); // Outputs: 'Default Name' 15 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_06/L06S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L06S02 - Logical assignment operator &&= 3 | // 4 | 5 | // Consider a scenario where we want to append text to a string if it already has a value. 6 | let statusMessage = 'Processing'; 7 | 8 | // Using &&= to append only if statusMessage is truthy. 9 | statusMessage &&= statusMessage + ', please wait...'; 10 | gs.info(statusMessage); // Outputs: 'Processing, please wait...' 11 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_07/L07S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L07S01 - Template literals 3 | // 4 | 5 | // Traditional string concatenation 6 | let user = 'John Doe'; 7 | let welcomeMessage = 'Hello, ' + user + '! Welcome to ServiceNow.'; 8 | gs.info(welcomeMessage); 9 | 10 | // Using template literals 11 | let welcomeMessageLiteral = `Hello, ${user}! Welcome to ServiceNow.`; 12 | gs.info(welcomeMessageLiteral); 13 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_08/L08S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L08S01 - String padding 3 | // 4 | 5 | // Example using padStart 6 | let accountNumber = '12345'; 7 | let paddedAccountNumber = accountNumber.padStart(10, '0'); 8 | gs.info('Padded Account Number: ' + paddedAccountNumber); // Outputs: 0000012345 9 | 10 | // Example using padEnd 11 | let shortRemark = 'OK'; 12 | let paddedRemark = shortRemark.padEnd(5, '.'); 13 | gs.info('Padded Remark: ' + paddedRemark); // Outputs: OK... 14 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_09/L09S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L09S01 - startsWith() and endsWith() 3 | // 4 | 5 | // Example using startsWith 6 | let incidentDescription = 'Error 503: Service Unavailable'; 7 | if (incidentDescription.startsWith('Error')) { 8 | gs.info('This is an error message.'); 9 | } 10 | 11 | // Example using endsWith 12 | let filename = 'report.pdf'; 13 | if (filename.endsWith('.pdf')) { 14 | gs.info('The file is a PDF document.'); 15 | } 16 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_09/L09S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L09S02 - trimStart() and trimEnd() 3 | // 4 | 5 | // Example using trimStart and trimEnd 6 | let userInput = ' ServiceNow '; 7 | let trimmedStartInput = userInput.trimStart(); 8 | gs.info('Trimmed Input: "' + trimmedStartInput + '"'); 9 | 10 | let trimmedEndInput = userInput.trimEnd(); 11 | gs.info('Trimmed Input: "' + trimmedEndInput + '"'); -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_10/L10S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L10S01 - matchAll() 3 | // 4 | 5 | // A string with repeated patterns. 6 | let logData = 'Error: 404. Error: 500. Error: 403.'; 7 | 8 | // Using matchAll to find all error codes. 9 | let errorPattern = /Error: (\d+)/g; 10 | let matches = logData.matchAll(errorPattern); 11 | 12 | // Iterating over matches to log all error codes. 13 | for (let match of matches) { 14 | gs.info('Found error code: ' + match[1]); 15 | } 16 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_10/L10S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L10S02 - includes() 3 | // 4 | 5 | // Checking if a string includes a specific substring. 6 | let errorMessage = 'Fatal error: System shutdown'; 7 | 8 | // Using includes to check for a specific word. 9 | if (errorMessage.includes('Fatal')) { 10 | gs.info('Critical issue found!'); 11 | } 12 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_11/L11S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L11S01 - Basic Arrow Function syntax 3 | // 4 | 5 | // Traditional function syntax 6 | function add(a, b) { 7 | return a + b; 8 | } 9 | 10 | // Arrow function syntax 11 | const addArrow = (a, b) => a + b; 12 | gs.info('Addition using Arrow Function: ' + addArrow(5, 3)); // Outputs: 8 -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_11/L11S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L11S02 - Arrow Functions in object methods and how it interacts with `this` 3 | // 4 | 5 | var user = { 6 | name: 'John Doe', 7 | logName: () => { 8 | gs.info(this.name); // 'this' refers to the global object, not 'user' 9 | } 10 | }; 11 | user.logName(); // Outputs: undefined 12 | 13 | function otherContext(){ 14 | this.name = "Abel"; 15 | user.logName(); 16 | } 17 | 18 | otherContext(); // 'Abel' is printed because 'this' context is maintained -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_12/L12S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L12S01 - Default parameters in functions 3 | // 4 | 5 | function createIncident(description, priority = 'Low') { 6 | gs.info(`Creating incident with description: ${description} and priority: ${priority}`); 7 | } 8 | 9 | createIncident('Login issue'); // Uses default priority 'Low' 10 | createIncident('Server outage', 'High'); // Uses provided priority 'High' -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_12/L12S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L12S02 - Using Default Parameters effectively 3 | // 4 | 5 | // More complex default parameter usage 6 | function logMessage(message, timestamp = new Date().toISOString()) { 7 | gs.info(`[${timestamp}] ${message}`); 8 | } 9 | 10 | logMessage('User logged in'); // Timestamp is set to the current time 11 | logMessage('User logged out', '2023-04-01T10:00:00.000Z'); // Specified timestamp is used 12 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_13/L13S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L13S01 - the Rest Operator 3 | // 4 | 5 | function logIncidents(...incidentIds) { 6 | incidentIds.forEach(id => gs.info('Logging Incident ID: ' + id)); 7 | } 8 | 9 | logIncidents('INC001', 'INC002', 'INC003'); // Logs each Incident ID -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_13/L13S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L13S02 - The Spread Operator 3 | // 4 | 5 | // Combining arrays using the Spread operator 6 | let firstBatch = ['INC004', 'INC005']; 7 | let secondBatch = ['INC006', 'INC007']; 8 | let combinedBatches = [...firstBatch, ...secondBatch]; 9 | gs.info('Combined Incident IDs: ' + combinedBatches.join(', ')); 10 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_14/L14S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L14S01 - The "name" property 3 | // 4 | 5 | // Named function 6 | function myFunction() {} 7 | gs.info('Function name: ' + myFunction.name); // Outputs: myFunction 8 | 9 | // Anonymous function assigned to a variable 10 | var anonymousFunction = function() {}; 11 | gs.info('Anonymous function name: ' + anonymousFunction.name); // Outputs: anonymousFunction 12 | 13 | // the first one worked before ES2021, but the second one didn't! -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_14/L14S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L14S02 - Practical use in ServiceNow 3 | // 4 | 5 | // Using the name property in a function array 6 | var functionsArray = [function firstFunc() {}, function secondFunc() {}]; 7 | 8 | functionsArray.forEach(func => { 9 | gs.info('Processing function: ' + func.name); 10 | }); 11 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_15/L15S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L15S01 - Trailing commas in function definitions 3 | // 4 | 5 | function createTask(title, description, ) { 6 | gs.info(`Task created with title: ${title} and description: ${description}`); 7 | } 8 | 9 | createTask('Review Code', 'Check the latest commit.'); 10 | 11 | // Function call with trailing comma 12 | createTask( 13 | 'Update Documentation', 14 | 'Add details about new features', 15 | ); -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_16/L16S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L16S01 - Shorthand properties and methods 3 | // 4 | 5 | let userId = 'u123'; 6 | let userName = 'John Doe'; 7 | 8 | let userObj = { 9 | userId, // Shorthand property 10 | userName, 11 | logDetails() { // Shorthand method 12 | gs.info(`User: ${this.userId}, Name: ${this.userName}`); 13 | } 14 | }; 15 | 16 | userObj.logDetails(); // Outputs: User: u123, Name: John Doe 17 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_16/L16S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L16S02 - Computed property names 3 | // 4 | 5 | let propName = 'status'; 6 | let serviceNowObject = { 7 | ['is' + propName.charAt(0).toUpperCase() + propName.slice(1)]: true, // Computed property name 8 | checkStatus() { 9 | gs.info('Status is: ' + this.isStatus); 10 | } 11 | }; 12 | 13 | serviceNowObject.checkStatus(); // Outputs: Status is: true 14 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_17/L17S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L17S01 - Basic class structure 3 | // 4 | 5 | // Defining a simple class 6 | class Incident { 7 | constructor(id, description) { 8 | this.id = id; 9 | this.description = description; 10 | } 11 | 12 | logDetails() { 13 | gs.info(`Incident ${this.id}: ${this.description}`); 14 | } 15 | } 16 | 17 | let incident = new Incident('INC001', 'Login failure'); 18 | incident.logDetails(); // Logs: Incident INC001: Login failure -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_17/L17S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L17S02 - Class inheritence 3 | // 4 | 5 | // From L17S01 6 | class Incident { 7 | constructor(id, description) { 8 | this.id = id; 9 | this.description = description; 10 | } 11 | 12 | logDetails() { 13 | gs.info(`Incident ${this.id}: ${this.description}`); 14 | } 15 | } 16 | 17 | // Extending a class 18 | class SecurityIncident extends Incident { 19 | constructor(id, description, securityLevel) { 20 | super(id, description); 21 | this.securityLevel = securityLevel; 22 | } 23 | 24 | logSecurityDetails() { 25 | gs.info(`Security Incident ${this.id}: ${this.description}, Level: ${this.securityLevel}`); 26 | } 27 | } 28 | 29 | let secIncident = new SecurityIncident('INC002', 'Unauthorized access', 'High'); 30 | secIncident.logSecurityDetails(); // Logs: Security Incident INC002: Unauthorized access, Level: High 31 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_18/L18S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L18S01 - Creating and using Symbols 3 | // 4 | 5 | // Creating a Symbol 6 | let mySymbol = Symbol('my unique symbol'); 7 | 8 | // Using Symbol as a property key 9 | let myObject = { 10 | [mySymbol]: 'Symbol Value' 11 | }; 12 | 13 | gs.info(myObject[mySymbol]); // Outputs: Symbol Value 14 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_18/L18S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L18S02 - Symbols for private properties 3 | // 4 | 5 | const secretKey = Symbol('secretKey'); 6 | class SecretHolder { 7 | constructor(secret) { 8 | this[secretKey] = secret; 9 | } 10 | 11 | revealSecret() { 12 | return this[secretKey]; 13 | } 14 | } 15 | 16 | let holder = new SecretHolder('MySecret'); 17 | 18 | gs.info (holder.secretKey); // Outputs: undefined 19 | for (let i in Object.getOwnPropertyNames(Object.getPrototypeOf(holder))){ 20 | gs.info(i + ': ' + holder[i]); //Outputs: undefined 21 | } 22 | 23 | gs.info(holder.revealSecret()); // Outputs: MySecret -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_19/L19S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L19S01 - Using optional chaining with objects 3 | // 4 | 5 | // Example object 6 | let incidentRecord = { 7 | incident: { 8 | id: 'INC001', 9 | details: { 10 | description: 'Login issue', 11 | assignedTo: 'John Doe' 12 | } 13 | } 14 | }; 15 | 16 | // Accessing nested properties with optional chaining 17 | let assignedTo = incidentRecord.incident?.details?.assignedTo; 18 | gs.info('Assigned to: ' + assignedTo); // Outputs: John Doe -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_19/L19S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L19S02 - Optional chaining with function calls 3 | // 4 | 5 | // Object with a method 6 | let user = { 7 | profile: { 8 | getName: function () { 9 | return 'Jane Smith'; 10 | } 11 | } 12 | }; 13 | 14 | // Safely calling a method 15 | let userName = user.profile?.getName?.(); 16 | gs.info('User name: ' + userName); // Outputs: Jane Smith -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_20/L20S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L20S03 - Object.getOwnPropertyDescriptors() 3 | // 4 | 5 | // From L20S01 6 | 7 | let incident = { 8 | id: 'INC001', 9 | status: 'Open', 10 | priority: 'High' 11 | }; 12 | 13 | // Getting property descriptors of an object 14 | let descriptors = Object.getOwnPropertyDescriptors(incident); 15 | gs.info('Descriptors: ' + JSON.stringify(descriptors, null, 4)); 16 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_20/L20S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L20S02 - Object.fromEntries() 3 | // 4 | 5 | // Converting entries back to an object 6 | let incidentEntries = [['id', 'INC002'], ['status', 'Closed'], ['priority', 'Low']]; 7 | let newIncident = Object.fromEntries(incidentEntries); 8 | gs.info('New Incident: ' + JSON.stringify(newIncident)); 9 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_21/L21S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L21S01 - for...of loops on arrays (vs. for...in) 3 | // 4 | 5 | let incidentIds = ['INC001', 'INC002', 'INC003']; 6 | 7 | // Reminder of for...in 8 | for (let id in incidentIds) { 9 | gs.info('Processing Incident: ' + incidentIds[id]); 10 | } 11 | 12 | // Iterating over an array with for...of 13 | for (let id of incidentIds) { 14 | gs.info('Processing Incident: ' + id); 15 | } 16 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_21/L21S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L21S02 - for...of on strings 3 | // 4 | 5 | // Iterating over a string 6 | let status = 'Resolved'; 7 | 8 | for (let letter of status) { 9 | gs.info('Letter: ' + letter); 10 | } 11 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_22/L22S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L22S01 - Map() 3 | // 4 | 5 | // Creating and using a Map 6 | let incidentMap = new Map(); 7 | 8 | // Adding key-value pairs 9 | incidentMap.set('INC001', 'Login issue'); 10 | incidentMap.set('INC002', 'Email not working'); 11 | 12 | // Retrieving a value 13 | gs.info('INC001 Description: ' + incidentMap.get('INC001')); // Outputs: Login issue 14 | 15 | // Iterating over Map entries 16 | incidentMap.forEach((value, key) => { 17 | gs.info(`Incident ${key}: ${value}`); 18 | }); 19 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_22/L22S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L22S02 - Set() 3 | // 4 | 5 | // Creating and using a Set 6 | let uniqueIncidentSet = new Set(); 7 | 8 | // Adding values 9 | uniqueIncidentSet.add('INC001'); 10 | uniqueIncidentSet.add('INC002'); 11 | uniqueIncidentSet.add('INC001'); // Duplicate, won't be added 12 | 13 | // Checking the size and iterating over Set 14 | gs.info('Number of unique incidents: ' + uniqueIncidentSet.size); // Outputs: 2 15 | for (let incident of uniqueIncidentSet) { 16 | gs.info('Unique Incident: ' + incident); 17 | } 18 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_23/L23S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L23S0 - Array.from() 3 | // 4 | 5 | // Creating an array from a string 6 | let incidentString = 'INC001'; 7 | let incidentArray = Array.from(incidentString); 8 | gs.info('Array from string: ' + incidentArray.join(', ')); // Outputs: I, N, C, 0, 0, 1 9 | 10 | // Creating an array from a Set 11 | let incidentSet = new Set(['INC002', 'INC003', 'INC004']); 12 | let incidents = Array.from(incidentSet); 13 | gs.info('Array from set: ' + incidents.join(', ')); // Outputs: INC002, INC003, INC004 14 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_23/L23S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L23S02 - Array.of() 3 | // 4 | 5 | // Creating arrays with Array.of() 6 | let numbers = Array.of(1, 2, 3); 7 | gs.info('Numbers array: ' + numbers.join(', ')); // Outputs: 1, 2, 3 8 | 9 | let words = Array.of('ServiceNow', 'Scripting'); 10 | gs.info('Words array: ' + words.join(', ')); // Outputs: ServiceNow, Scripting 11 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_24/L24S01.js: -------------------------------------------------------------------------------- 1 | // 2 | // L24S01 - flat() 3 | // 4 | 5 | // Flattening nested arrays with flat() 6 | let nestedArray = [1, [2, 3], [4, [5, 6]]]; 7 | let flatArray = nestedArray.flat(2); 8 | gs.info('Flattened Array: ' + flatArray.join(', ')); // Outputs: 1, 2, 3, 4, 5, 6 9 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Lesson_24/L24S02.js: -------------------------------------------------------------------------------- 1 | // 2 | // L24S02 - flatMap() 3 | // 4 | 5 | // Combining mapping and flattening with flatMap() 6 | let incidentArray = [{ 7 | id: 'INC001', 8 | notes: ['Login issue', 'User cannot access'] 9 | }, 10 | { 11 | id: 'INC002', 12 | notes: ['Email issue'] 13 | } 14 | ]; 15 | 16 | let notes = incidentArray.flatMap(incident => incident.notes.map(note => `Note: ${note}`)); 17 | gs.info('All Notes: ' + notes.join('; ')); // Outputs: Note: Login issue; Note: User cannot access; Note: Email issue -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Scrapped_exercises/Lesson_00_what_happend.md: -------------------------------------------------------------------------------- 1 | All lesson exercises for the "Let's Learn ECMAScript 2021" series originally were recorded as videos but the pacing of the series felt way off due to the fact that some exercise videos were longer than the lesson themselves. Thus, all lesson videos were shelved. I was about to delete the lesson exercise files from this repository but decided to leave them here in a separate folder just in case someone out there is interestd. 2 | 3 | Enjoy! -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Scrapped_exercises/Lesson_01_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Create a script that defines a constant representing the maximum number of users allowed on a ServiceNow instance. Then, use a let variable to track the current number of users and increment it until it reaches the maximum. Log an alert when the maximum is reached. 3 | 4 | Hints: 5 | Initialize the constant with a value like 100. 6 | Use a loop to increment the current user count. 7 | Compare the current user count with the maximum in each iteration. 8 | */ 9 | 10 | // Solution 11 | 12 | const MAX_USERS = 100; 13 | let currentUserCount = 0; 14 | 15 | while (currentUserCount < MAX_USERS) { 16 | currentUserCount++; 17 | } 18 | 19 | gs.info('Maximum user count of ' + MAX_USERS + ' reached'); 20 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Scrapped_exercises/Lesson_02_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a script where a let variable is declared but not initialized and is used within a function that is called before the variable is initialized. Identify the Temporal Dead Zone error and modify the code to fix it. 3 | 4 | Hints: 5 | Declare the variable at the top of your script but don’t assign any value. 6 | Access the variable inside a function which is called before the variable initialization line. 7 | */ 8 | 9 | let myVar; 10 | 11 | function logVar() { 12 | gs.info(myVar); 13 | } 14 | 15 | logVar(); 16 | myVar = 10; 17 | 18 | // Solution 19 | 20 | let myVar2; 21 | 22 | function logVar2() { 23 | gs.info(myVar2); 24 | } 25 | 26 | // Temporal Dead Zone error occurs if logVar is called here. 27 | myVar2 = 10; 28 | logVar2(); // Call after initialization to avoid TDZ error. 29 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Scrapped_exercises/Lesson_03_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Create a function that calculates and returns the volume of a cube. Use the exponentiation operator to calculate the volume. 3 | 4 | Hints: 5 | The volume of a cube is the side length raised to the power of 3. 6 | Use the exponentiation operator ** in your calculation. 7 | */ 8 | 9 | function cubeVolume(side) { 10 | return side ** 3; 11 | } 12 | 13 | let volume = cubeVolume(5); 14 | gs.info('Volume of the cube: ' + volume); -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Scrapped_exercises/Lesson_04_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a script where a function receives an object representing a ServiceNow user. The function should return the user's email, but if the email property is null or undefined, it should return a default email. 3 | 4 | Hints: 5 | Use the nullish coalescing operator ?? to provide a fallback value. 6 | Assume the function parameter is an object with a possibly null or undefined email property. 7 | */ 8 | 9 | // Solution 10 | 11 | function getUserEmail(user) { 12 | return user.email ?? 'default@email.com'; 13 | } 14 | 15 | let user = { 16 | name: 'John Doe', 17 | email: null 18 | }; 19 | gs.info('User email: ' + getUserEmail(user)); -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Scrapped_exercises/Lesson_05_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Create a script that defines a large numeric constant representing the total number of milliseconds in a year. Use numeric separators to make the number more readable, then calculate and log how many seconds that is. 3 | 4 | Hints: 5 | There are 1,000 milliseconds in a second, 3,600 seconds in an hour, 24 hours in a day, and approximately 365 days in a year. 6 | Use underscores _ as numeric separators. 7 | */ 8 | 9 | // Solution 10 | 11 | const MILLISECONDS_IN_YEAR = 365 * 24 * 3_600 * 1_000; 12 | let secondsInYear = MILLISECONDS_IN_YEAR / 1_000; 13 | gs.info('Seconds in a year: ' + secondsInYear); 14 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Scrapped_exercises/Lesson_06_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | You have a script that initializes an object to hold configuration settings for a ServiceNow application. Use the logical assignment operators to set default values for two properties: isEnabled (should default to true) and maxUsers (should default to 100), but only if they haven’t been set yet. 3 | 4 | Hints: 5 | Start with an object that may or may not have isEnabled and maxUsers properties. 6 | Use ||= to default isEnabled to true and &&= to set maxUsers only if it already has a truthy value. 7 | */ 8 | 9 | // Solution 10 | 11 | let config = { maxUsers: 50 }; 12 | 13 | config.isEnabled ||= true; 14 | config.maxUsers &&= 100; 15 | 16 | gs.info('Config: ' + JSON.stringify(config)); 17 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Scrapped_exercises/Lesson_07_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Exercise: 3 | Create a template literal that generates a detailed log message for a ServiceNow incident. Include the incident's number, state, and priority. 4 | The log message should read like: 'Incident INC0012345 is currently in the Resolved state with a priority of 1 - Critical.' 5 | Use dummy variables for the incident details, and construct the message in a single template literal. 6 | 7 | Hints: 8 | Declare your variables before the template literal. 9 | Remember to use ${} to insert these variables into your string. 10 | */ 11 | 12 | // Solution 13 | 14 | var incidentNumber = 'INC0012345'; 15 | var incidentState = 'Resolved'; 16 | var incidentPriority = '1 - Critical'; 17 | 18 | var logMessage = `Incident ${incidentNumber} is currently in the ${incidentState} state with a priority of ${incidentPriority}.`; 19 | gs.info(logMessage); 20 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Scrapped_exercises/Lesson_08_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Create a template literal that generates a detailed log message for a ServiceNow incident. Include the incident's number, state, and priority. 3 | The log message should read like: 'Incident INC0012345 is currently in the Resolved state with a priority of 1 - Critical.' 4 | Use dummy variables for the incident details, and construct the message in a single template literal. 5 | 6 | Hints: 7 | Declare your variables before the template literal. 8 | Remember to use ${} to insert these variables into your string. 9 | */ 10 | 11 | // Solution 12 | 13 | function createDepartmentIdentifier(deptCode, uniqueNumber) { 14 | return deptCode + uniqueNumber.toString().padStart(8 - deptCode.length, '0'); 15 | } 16 | 17 | let identifier = createDepartmentIdentifier('IT', 123); 18 | gs.info('Department Identifier: ' + identifier); // Outputs: IT000123 -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Scrapped_exercises/Lesson_09_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Consider a scenario where you're processing user-generated content in ServiceNow: 3 | 4 | You receive a string of text input, which might have extraneous whitespace at the beginning or end and could start with a timestamp. 5 | Write a script that checks if the input starts with a the string `Start`. If it does, log 'Start found'. Then, remove any extra whitespace from the start and end of the string. 6 | Validate your script with different inputs. 7 | 8 | Hints: 9 | Use startsWith() to see if the keyword is at the start of the string. 10 | Use trimStart() and trimEnd() to remove unnecessary whitespace. 11 | */ 12 | 13 | // Solution 14 | 15 | function processInput(input) { 16 | let inputCheck = 'Start'; 17 | if (input.startsWith(inputCheck)) { 18 | gs.info('Start found'); 19 | } else if (input.includes(inputCheck)){ 20 | gs.info('Start found but not at beginning'); 21 | } else { 22 | gs.info('Start not found'); 23 | } 24 | 25 | let trimmedInput = input.trimStart().trimEnd(); 26 | gs.info('Processed Input: "' + trimmedInput + '"'); 27 | } 28 | 29 | processInput(' Start Report '); 30 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Scrapped_exercises/Lesson_10_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Imagine you're analyzing a text field from incident records in ServiceNow, looking for specific keywords to categorize the incident. Your task is to: 3 | 4 | Write a function that takes an incident description as input. 5 | Use includes() to check for keywords like 'crash', 'slow', or 'unavailable' and categorize the incident based on these. 6 | Additionally, use matchAll() to extract any error codes formatted like 'E123' and log them. 7 | 8 | Hints: 9 | Combine includes() with conditional statements. 10 | You can use the regular expression /E(\d+)/g to match the error code pattern and use matchAll(). 11 | Print a gs.info() log instead of actually categorizing something. 12 | */ 13 | 14 | // Solution 15 | 16 | function categorizeIncident(description) { 17 | if (description.includes('crash')) { 18 | gs.info('Category: Crash Issue'); 19 | } else if (description.includes('slow')) { 20 | gs.info('Category: Performance Issue'); 21 | } else if (description.includes('unavailable')) { 22 | gs.info('Category: Availability Issue'); 23 | } 24 | 25 | let errorCodePattern = /E(\d+)/g; 26 | let matches = description.matchAll(errorCodePattern); 27 | for (let match of matches) { 28 | gs.info('Extracted error code: ' + match[1]); 29 | } 30 | } 31 | 32 | // Example use 33 | categorizeIncident('System crash observed. Errors: E404, E500.'); -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Scrapped_exercises/Lesson_11_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | I'm going to give you a script include (don't worry, it can run in a background script). Change the arrow function to display the given Task ID and Description. Bonus points for using template literals! 3 | 4 | Hints: 5 | The only edit needed is on the `const formatDetails = () => '';` line 6 | The output should look like "Task ID: 123, Description: Complete documentation" 7 | */ 8 | 9 | var Task = Class.create(); 10 | Task.prototype = { 11 | initialize: function(id, description) { 12 | this.id = id; 13 | this.description = description; 14 | }, 15 | 16 | logDetails: function() { 17 | const formatDetails = () => ''; 18 | gs.info(formatDetails()); 19 | } 20 | }; 21 | 22 | var myTask = new Task('123', 'Complete documentation'); 23 | myTask.logDetails(); 24 | 25 | // Solution 26 | 27 | var Task = Class.create(); 28 | Task.prototype = { 29 | initialize: function(id, description) { 30 | this.id = id; 31 | this.description = description; 32 | }, 33 | 34 | logDetails: function() { 35 | const formatDetails = () => `Task ID: ${this.id}, Description: ${this.description}`; 36 | gs.info(formatDetails()); 37 | } 38 | }; 39 | 40 | var myTask = new Task('123', 'Complete documentation'); 41 | myTask.logDetails(); // Outputs: Task ID: 123, Description: Complete documentation 42 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Scrapped_exercises/Lesson_12_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function assignToGroup that assigns a task to a group. The function should take two parameters: taskId and groupId, with groupId having a default value. 3 | If groupId is not provided, the task should be assigned to a default 'General Support' group. 4 | Test this function by passing only the taskId and then with both taskId and groupId. 5 | 6 | Hints: 7 | Use a fictional default group ID for 'General Support'. 8 | Simulate the function's operation using gs.info to output the assignment. 9 | */ 10 | 11 | // Solution 12 | 13 | function assignToGroup(taskId, groupId = '00a1b2c3d4e5f67890123456') { 14 | let groupName = groupId === '00a1b2c3d4e5f67890123456' ? 'General Support' : 'Specific Group'; 15 | gs.info(`Task ${taskId} assigned to group ${groupName}`); 16 | } 17 | 18 | assignToGroup('abc123'); // Assumes default group assignment 19 | assignToGroup('abc123', '1234abcd5678efgh'); // Assigns to specified group -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Scrapped_exercises/Lesson_13_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function mergeTasks that merges two arrays of task IDs into one. 3 | The function should take two arrays as arguments and return a new array containing all unique task IDs, using the Spread operator. 4 | 5 | Hints: 6 | Use the Spread operator to combine arrays. 7 | */ 8 | 9 | // Solution 10 | 11 | function mergeTasks(array1, array2) { 12 | let combinedArray = [...array1, ...array2]; 13 | return [...new Set(combinedArray)]; //Preview of a future lesson! 14 | } 15 | 16 | let tasks1 = ['TASK001', 'TASK002', 'TASK003']; 17 | let tasks2 = ['TASK002', 'TASK004']; 18 | let mergedTasks = mergeTasks(tasks1, tasks2); 19 | gs.info('Merged Tasks: ' + mergedTasks.join(', ')); -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Scrapped_exercises/Lesson_14_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Imagine you're writing a script in ServiceNow where you need to log the execution of various functions for debugging: 3 | 4 | Create an array of three functions, each with a unique purpose (e.g., logging, calculating, processing). 5 | Iterate over this array and execute each function. 6 | As each function executes, use its name property to log a message indicating which function is currently running. 7 | 8 | Hints: 9 | Define each function with a descriptive name. 10 | Use a for...in loop to iterate and invoke each function within the array. 11 | */ 12 | 13 | var logFunction = function logActivity() { /* ... */ }; 14 | var calculateFunction = function calculateValues() { /* ... */ }; 15 | var processFunction = function processData() { /* ... */ }; 16 | 17 | // Solution 18 | 19 | var logFunction = function logActivity() { /* ... */ }; 20 | var calculateFunction = function calculateValues() { /* ... */ }; 21 | var processFunction = function processData() { /* ... */ }; 22 | 23 | var functionArray = [logFunction, calculateFunction, processFunction]; 24 | 25 | for (var func in functionArray){ 26 | gs.info('Executing function: ' + functionArray[func].name); 27 | } 28 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Scrapped_exercises/Lesson_16_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Let's apply these enhancements in a ServiceNow context: 3 | Create an object incidentReporter that includes properties incidentId, description, and a method reportIncident. 4 | Use shorthand properties to initialize incidentId and description from existing variables. 5 | Implement reportIncident as a shorthand method that logs the incident details. 6 | Add a computed property based on a string 'isStatus' which is set to 'Open'. 7 | */ 8 | 9 | var incidentId = 'INC001'; 10 | var description = 'Login issue'; 11 | 12 | var incidentReporter = { 13 | // your code here! 14 | }; 15 | 16 | // Solution 17 | 18 | var incidentId = 'INC001'; 19 | var description = 'Login issue'; 20 | 21 | var incidentReporter = { 22 | incidentId, 23 | description, 24 | reportIncident() { 25 | gs.info(`Reporting Incident: ${this.incidentId}, Description: ${this.description}`); 26 | }, 27 | ['is' + 'Status']: 'Open' 28 | }; 29 | 30 | incidentReporter.reportIncident(); // Outputs: Reporting Incident: INC001, Description: Login issue 31 | gs.info('Incident Status: ' + incidentReporter.isStatus); // Outputs: Incident Status: Open 32 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Scrapped_exercises/Lesson_17_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Create a ServiceNow Script Include representing a class User with properties like name and email. Then extend this class with a subclass AdminUser that adds additional properties and methods. Demonstrate creating instances of these classes and using their methods. 3 | */ 4 | 5 | // Solution 6 | 7 | // User class 8 | class User { 9 | constructor(name, email) { 10 | this.name = name; 11 | this.email = email; 12 | } 13 | 14 | logDetails() { 15 | gs.info(`User: ${this.name}, Email: ${this.email}`); 16 | } 17 | } 18 | 19 | // AdminUser class 20 | class AdminUser extends User { 21 | constructor(name, email, accessLevel) { 22 | super(name, email); 23 | this.accessLevel = accessLevel; 24 | } 25 | 26 | logAdminDetails() { 27 | gs.info(`Admin User: ${this.name}, Access Level: ${this.accessLevel}`); 28 | } 29 | } 30 | 31 | let user = new User('John Doe', 'john.doe@example.com'); 32 | user.logDetails(); 33 | 34 | let admin = new AdminUser('Jane Smith', 'jane.smith@example.com', 'High'); 35 | admin.logAdminDetails(); -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Scrapped_exercises/Lesson_19_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a script that accesses a nested property within a GlideRecord object, such as the name of an assigned user in an incident record. 3 | Ensure that your script handles cases where the nested property or its parent objects might not exist. 4 | Log the accessed property or a message indicating that it's not available. 5 | 6 | Hints: 7 | Query an incident record and try to access a nested property that may not be present. 8 | Use Optional Chaining to avoid a null or undefined error. 9 | */ 10 | 11 | // Solution 12 | 13 | var incGr = new GlideRecord('incident'); 14 | incGr.query(); 15 | if (incGr.next()) { 16 | var assignedUserName = incGr.assigned_to?.getRefRecord()?.getValue('name'); 17 | gs.info('Assigned User Name: ' + (assignedUserName || 'Not assigned')); 18 | } -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Scrapped_exercises/Lesson_20_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Convert a GlideRecord object of an incident into a standard JavaScript object. 3 | Use Object.entries() to log each field and its value. 4 | Modify some values and use Object.fromEntries() to convert it back to an object. 5 | Finally, use Object.getOwnPropertyDescriptors() to inspect one of the modified properties. 6 | 7 | Hints: 8 | Utilize GlideRecord to fetch an incident and convert it into a JavaScript object. 9 | Manipulate the object and its properties using the methods discussed. 10 | */ 11 | 12 | var incGr = new GlideRecord('incident'); 13 | incGr.query(); 14 | if (incGr.next()) { 15 | var incidentObj = {}; 16 | for (var field in incGr) { 17 | if (incGr.isValidField(field)) { 18 | incidentObj[field] = incGr.getValue(field); 19 | } 20 | } 21 | 22 | var entries = Object.entries(incidentObj); 23 | entries.forEach(entry => { 24 | gs.info('Field: ' + entry[0] + ', Value: ' + entry[1]); 25 | }); 26 | 27 | // Modifying an entry 28 | entries[0][1] = 'INC003'; 29 | var modifiedIncident = Object.fromEntries(entries); 30 | 31 | var descriptor = Object.getOwnPropertyDescriptors(modifiedIncident); 32 | gs.info('Descriptor of modified property: ' + JSON.stringify(descriptor.parent, null, 4)); 33 | } -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Scrapped_exercises/Lesson_21_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Create a function logWorkNotes that takes an array of work notes (strings). 3 | Iterate over this array using a for...of loop and log each note. 4 | Additionally, include a counter to indicate the note's position in the array. 5 | 6 | Hints: 7 | Use a variable to keep track of the current index. 8 | Use template literals for logging to include the index and note. 9 | */ 10 | 11 | // Solution 12 | 13 | function logWorkNotes(notes) { 14 | let index = 1; 15 | for (let note of notes) { 16 | gs.info(`Note ${index}: ${note}`); 17 | index++; 18 | } 19 | } 20 | 21 | logWorkNotes(['Hello1', 'Hello2', 'Hello3']); -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Scrapped_exercises/Lesson_22_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Let's try utilizing a map with an arrow function (this happens a lot in JavaScript, and you'll see it often on stackexchange!) 3 | 4 | Create a function named "convertToUpperCase" that takes an array of strings. 5 | Use the map method along with an arrow function to create a new array where each string is converted to uppercase. 6 | 7 | Hints: 8 | - Use the map method to iterate over the array and transform each element. 9 | - Inside the map, use an arrow function to return the uppercase version of each string. 10 | - Remember that strings have a toUpperCase() method. 11 | */ 12 | 13 | // Solution 14 | 15 | function convertToUpperCase(strings) { 16 | return strings.map(string => string.toUpperCase()); 17 | } 18 | 19 | // Example usage 20 | gs.info(convertToUpperCase(['hello', 'world'])); // Outputs: HELLO,WORLD 21 | -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Scrapped_exercises/Lesson_23_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function convertToIncidentArray that takes an argument and returns an array of incident IDs using Array.from(). The argument could be a string, a Set, or an array. 3 | Use Array.of() to create an array from individual incident ID arguments and log the result. 4 | Test your function with different types of inputs to ensure it always returns an array of incident IDs. 5 | 6 | Hints: 7 | Check the type of the input argument in convertToIncidentArray to handle different types. 8 | Use Array.isArray() to check if the input is already an array. 9 | */ 10 | 11 | // Solution 12 | 13 | function convertToIncidentArray(input) { 14 | if (Array.isArray(input)) { 15 | return input; 16 | } 17 | return Array.from(input); 18 | } 19 | 20 | let incidentsString = 'INC005'; 21 | let incidentsSet = new Set(['INC006', 'INC007']); 22 | let incidentsArray = ['INC008', 'INC009']; 23 | 24 | gs.info('Array from String: ' + convertToIncidentArray(incidentsString).join(', ')); 25 | gs.info('Array from Set: ' + convertToIncidentArray(incidentsSet).join(', ')); 26 | gs.info('Array from Array: ' + convertToIncidentArray(incidentsArray).join(', ')); -------------------------------------------------------------------------------- /Section 3 - Lets learn ECMAScript 2021 (ES12) with Earl Duque/Scrapped_exercises/Lesson_24_Exercise.js: -------------------------------------------------------------------------------- 1 | /* 2 | Create a nested array representing categories and subcategories of incidents. Use flat() to flatten this array. 3 | Create an array of incidents where each incident has multiple work notes. Use flatMap() to create a flat array of formatted notes. 4 | Test and log the results of both operations. 5 | 6 | Hints: 7 | Structure the nested categories array with multiple levels of depth. 8 | Use a combination of mapping to format notes and then flatten the result. 9 | */ 10 | 11 | // Solution 12 | 13 | // Using flat() 14 | let categories = ['Software', ['Hardware', 'Peripheral'], ['Network', ['Internal', 'External']]]; 15 | let flattenedCategories = categories.flat(2); 16 | gs.info('Flattened Categories: ' + flattenedCategories.join(', ')); 17 | 18 | // Using flatMap() 19 | let incidents = [ 20 | { id: 'INC003', notes: ['Password reset', 'User guided'] }, 21 | { id: 'INC004', notes: ['Server downtime'] } 22 | ]; 23 | 24 | let formattedNotes = incidents.flatMap(incident => 25 | incident.notes.map(note => `Incident ${incident.id} Note: ${note}`) 26 | ); 27 | gs.info('Formatted Notes: ' + formattedNotes.join('; ')); 28 | --------------------------------------------------------------------------------