Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Falsy and Truthy and empty arrays in ServiceNow Javascript

Andy-L
Tera Contributor

As we know, GlideElements and other types of Glide objects can  be interpreted as false (falsy) depending on their underlying value, e.g.

if (incident_gr.active) { ... }

Even though the Javascript standard says the only things that are falsy are: false, 0, -0, 0n, "", null, undefined, NaN, and document.allUntil recently, I had assumed this was because Glide objects are not really JavaScript objects - but something else -  Java objects etc. However, the other day I was reviewing some code that I only wanted to run if a pure Javascript array object had at least one element:

 

var someArray = [];

callSomeFunctionThatMightAddElementsTo(someArray);

if (someArray) { 
    doSomething(); 
} 

 

Despite appearing wrong, from a pure JavaScript perspective (as an array is always Truthy according to the Javascript Specification), it worked perfectly! It should have been...

if (someArray && someArray.length ) { 
    doSomething(); 
}

 

Why didn't I need to change it? It appears that, in Server-Side JS, the empty array [] is also treated as false (contrary to the Standard).

 

For example, the following code outputs 'truthy' in the Browser dev console (client side), but 'falsy' in a background script.

console.log( [] ? 'truthy' : 'falsy' );

Just something to be aware of I guess! Especially if switching between client-side and server-side scripting. I've put up some notes here: Truthy/Falsy behaviour in ServiceNow Javascript.

 

 

0 REPLIES 0