- Post History
- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
on 04-30-2020 01:10 PM
In ServiceNow, the case of unintentionally working with a reference to a JavaScript object property instead of the property's value is most encountered in instances where you are iterating through the results of a GlideRecord query. Here is an example of this mistake and an explanation of why it occurs and how to avoid it.
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
The real issue here is that GlideRecord provides weak references. You're not allowed to keep the reference after GlideRecord decides to reuse the binding it gave you. This is unlike a typical pass-by-reference issue that you might experience in more traditional situations where you're dealing with strong references.
In reality, the core problem is that the properties are mutable and liable to disappear as soon as GlideRecord advances to the next item. The solution, as you say, is to cast the value in question into a Javascript primitive, but the Pros & Cons of each method for doing this need to be properly addressed!
In both given solutions from your article, you're stringifying the data. GlideRecord.getValue always returns a string, as does implictly casting the value via '' + GlideElement (or, alternatively, using the 'toString' method, which is effectively identical to casting via concatenation). That being said, getValue is not equivalent to an implicit cast! getValue has certain eccentricities, like turning booleans into "0"/"1". Implicit casting will handle such values in (imho) a much more correct fashion ("true"/"false").
Allow me to suggest a third option: the j2js Script Include that comes prepackaged in SNOW will automatically convert Java objects into JS equivalent data. This process inherently separates the output from the Weak reference, solving the problem without forcing you to use stringified output. j2js is, however, a bit slower in my experience. For simple applications, stringifying will often be enough to get the job done.
There's also the fact that, while j2js is very handy for working with individual GlideRecord properties, it won't gracefully handle processing an complete GlideRecord if you simply pass the entire object. See this article (shameless plug!) if you'd like to learn more about how to efficiently JS-ify entire GlideRecords in one go.