- Post History
- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
‎07-05-2023 05:00 PM - edited ‎07-11-2023 06:47 PM
Introduction:
ECMAScript (ES) is the standardized scripting language used to write JavaScript applications. With each new release, ECMAScript introduces various features that enhance the capabilities of JavaScript. In this blog post, we will explore the top ECMAScript features from ES6 to the latest version and evaluate their support in ServiceNow.
Support for ECMAScript in ServiceNow was introduced in the Tokyo release, thanks to the efforts of passionate members like myself who advocated for its inclusion. I am proud to have been one of the initial members who supported the idea and pushed for its implementation. You can find the original idea on the ServiceNow Idea Portal here. For those who are new or haven’t followed the latest changes, ServiceNow introduced support for latest ECMAScript features in Scoped Apps in the Tokyo release. It has improved since the Utah release. Unfortunately it is still not supported in Global scope but we are hoping that in the next few releases ServiceNow expand the support to Global applications.
This blog post is not about the detailed features of the ECMAScript. For a detailed explanation of each feature and its usage, refer to the external post here. I am evaluating the following features of ES6+ and if they are supported in ServiceNow or not:
- Arrow Functions
- Block-Scoped Variables (let and const)
- Template Literals
- Destructuring Assignment
- Spread Operator
- Classes
- Modules
- Promises
- Default Parameters
- Rest Parameters
- Object Literal Extensions
- Enhanced Object Properties
- Async/Await
- Symbol Type
- Set and Map Data Structures
- Optional Chaining
- Nullish Coalescing Operator
I have also created a custom App with ATF that tests these features. Please find the details here in my GitHub.
1. Supported ECMAScript Features:
ServiceNow has made significant strides in supporting modern JavaScript features. Here are some of the ECMAScript features that are fully supported in ServiceNow:
- Arrow Functions: Arrow functions provide a concise syntax for writing anonymous functions. They have a shorter syntax compared to traditional function expressions and lexically bind this value.
multiply = (a, b) => a * b;
- Block-Scoped Variables (let and const): The let and const keywords were introduced to declare block-scoped variables. Unlike var, which is function-scoped, let and const variables are limited to the block in which they are defined.
blockVariables() {
let x = 1;
const y = 2;
return x + y;
}
- Template Literals: Template literals allow embedding expressions and variables inside string literals using backticks (`). They support multi-line strings and provide an easy way to concatenate strings and variables.
templateLiterals(firstName, lastName) {
return `${firstName}, ${lastName}`;
}
- De-structuring Assignment: De-structuring assignment allows you to extract values from arrays or objects and assign them to variables using a concise syntax.
destructuringAssignment(person) {
const {
name,
age
} = person;
return name;
}
- Spread Operator: The spread operator allows you to expand elements of an iterable (like arrays or strings) or object properties into individual elements.
spreadOperator(array1, array2) {
return [...array1, ...array2]; // Merging two arrays
}
- Class syntax, allowing you to define classes and work with inheritance and object-oriented programming concepts more easily. This is an example of a Script Include class.
let Animal = class Animal{
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
};
- Inheritance: ES6+ enables proper Object-Oriented based inheritance that is now supported in ServiceNow.
// Sample inheritance
let Dog = class Dog extends Animal{
// Constructor and base class properties
constructor(name) {
super(name);
}
getName() {
return this.name;
}
};
- Default Parameters: Default parameters allow you to assign default values to function parameters if no value or undefined is passed when the function is called.
defaultParameter(parm = true) {
return parm;// returns true
}
- Object Literal Extensions: Object literal extensions provide shorthand syntax for defining object properties and methods. It allows you to define property keys without specifying a value if the key and value have the same name.
objectLiteralExtension(n, a) {
const name = n;
const age = a;
const person = {
name,
age
};
return person;
}
- Enhanced Object Properties: Enhanced object properties allow dynamic property assignment using variables and computed property names in object literals.
const name = 'John';
const age = 25;
const person = {
name,
age,
greet() {
console.log(`Hello, ${this.name}!`);
}
};
person.greet(); // Output: Hello, John!
- Symbol Type: Symbols are a new primitive data type introduced in ES6. They are unique and immutable, often used as property keys to avoid naming conflicts in objects.
symbols(value) {
const value1 = Symbol(value);
const value2 = Symbol(value);
return (value1 === value2);
}
- Set and Map Data Structures: ES6 introduced the Set and Map data structures. Set allows storing unique values of any type, while Map allows storing key-value pairs. Both provide helpful methods for working with data.
setDataStructure(value) {
const mySet = new Set([1, 2, 3]);
return mySet.has(value);
}
- Optional Chaining: Optional chaining (?.) allows accessing nested properties of an object without the need for explicit null or undefined checks. If a property in the chain is null or undefined, the result will be undefined.
optionalChaining() {
const person = {
name: 'John',
age: 25,
address: {
city: 'New York',
country: 'USA'
}
};
return person?.jobs?.location; // return undefined instead of blowing and run time error
}
- Nullish Coalescing Operator: The nullish coalescing operator (??) provides a concise way to choose a default value when a variable is null or undefined, excluding falsy values like empty strings or zero.
nullishCoalecing(name){
const displayName = name ?? 'Anonymous';
return displayName; // returns Anonymous if name is falsy
}
2. Not Supported ECMAScript Features:
Despite the continuous efforts to keep up with ECMAScript standards, ServiceNow may not yet support certain ECMAScript features. Here are a few ECMAScript features that are not supported in ServiceNow:
- Promises: are used to handle asynchronous operations in JavaScript. They represent a value that may be available now, in the future, or never. Promises simplify handling asynchronous code and provide better error handling using then() and catch() methods.
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data fetched successfully!');
}, 2000);
});
};
fetchData()
.then(data => console.log(data)) // Output: Data fetched successfully!
.catch(error => console.log(error));
- Async/Await: Async/await is a syntax introduced in ES8 that allows writing asynchronous code in a more synchronous manner. It simplifies working with Promises and provides a more readable and intuitive way to handle asynchronous operations.
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data fetched successfully!');
}, 2000);
});
};
async function fetchDataAsync() {
try {
const data = await fetchData();
console.log(data); // Output: Data fetched successfully!
} catch (error) {
console.log(error);
}
}
fetchDataAsync();
- Modules: Modules provide a way to organize and share code between multiple files. They allow you to import and export functions, objects, or values from one module to another.
export const greeting = 'Hello';
// ES6 (module2.js)
import { greeting } from './module1.js';
console.log(greeting); // Output: Hello
Conclusion:
ServiceNow has made remarkable progress in supporting modern ECMAScript features since the Tokyo release, thanks to the efforts of dedicated members who championed the idea. This has enabled developers to write more efficient and maintainable code on the platform. By understanding the supported, partially supported, and unsupported features, you can leverage the capabilities of ECMAScript while developing applications on the ServiceNow platform.
[Disclaimer: The availability and support of ECMAScript features in ServiceNow may vary based on the specific version and configuration of the platform. Always refer to official ServiceNow documentation for the most up-to-date information.]
- 9,436 Views
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Thank you, this is really helpful.
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Block-Scoped Variables (let and const) featured can't accept servicnow scripting
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
The Template Literals example does not work for me when scripting an RTE Entity Multiple Input Script Operation in Vancouver:
It does not like the grave/backquote character and will not allow a script to be saved containing one.
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
@S A Martin this feature currently works only on Scoped Applications. The Scoped Application needs to be configured to use ES6+. Not all OOTB scoped apps are configured yet but if you create a custom scoped app it should be configured by default.
Hope it helps.
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
The spread operator is not working in the server part of widgets in the portal... anyone know why?