Truthy/Falsy behaviour in ServiceNow Javascript

I had a strange issue the other day - I was reviewing some Javascript code in a Script Include I had written some time before. I was convinced it should have a bug, but it passed extensive testing with flying colours. The code was something like:
var error_array = getListOfErrorsOrReturnEmptyArray();
if (error_array) {
alertErrorCodes(error_array);
} else { // no errors
everythingIsAllGood();
}
The code was expecting an empty array to be treated as false. (ie. 'falsey' ) - I had written it shortly after doing some Python code. In Python an empty array is falsy. but in Javascript an empty array should be truthy:
"In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy. That is, all values are truthy except false, 0, -0, 0n, "", null, undefined, NaN, and document.all."
The code (in a pure Javascript perspective) should read something like :
if (error_array && error_array.length) {
alertErrorCodes(error_array);
} else { // no errors
...
}
So why did the original code work and treat an empty array as false? It was running as a server-side script on ServiceNow. It looks like ServiceNow have modified something so that empty arrays are treated at false. This is actually nicer in my opinion (Python does the same) - but it’s not standard Javascript.
Environment | Code | Output | [ ] |
Server | gs.info( [] ? 'something' : 'empty' ); | empty | Falsy |
Client / Standard JS | console.log( [] ? 'something' : 'empty' ); | something | Truthy |
This also reminded me of the way boolean glideElements also get the special truthy/falsy treatment: E.g.
if (incident_gr.active) doit();
If incident_gr.active were a normal JavaScript object in a normal JavaScript run-time this would always be truthy, but in the ServiceNow ServerSide environment, active is both a GlideElement object but can be falsy if the element value is falsy.
This is a perfectly acceptable (and somewhat encouraged) ServiceNow construct but would lead to errors outside of the ServiceNow ecosystem (even possibly in client-side scripts running in the browsers Javascript Run-Time). So it's not a portable construct if you plan to leverage JavaScript outside of ServiceNow..
Subscribe to my newsletter
Read articles from Andy Lord directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
