Determining if Something is an Array

I had an issue recently where I thought I was dealing with one kind of variable, but in fact was dealing with a different kind of variable.

During the course of debugging that particular block of code I realized that you can’t use typeof to determine whether or not something is an array.

Typeof returns ‘object’ for both an ‘object’:

const myObject = {

     “name”: “object 1”,

     “number”: 1

}

and an array:

let myArray = [1, 2, 3, 4]

As it turns out, there are at least two easy ways to determine whether or not something is an array.

Array.isArray() can be passed a variable and will return true if that variable is an array. Fortunately it is on old enough bit of functionality that it works with ServiceNow’s Rhino engine.

Additionally, ServiceNow’s gs.log() method will log out an array, but will log out ‘object’ for an object, so you can often tell what you’re dealing with just based on what you’re getting logged out as your script runs.

Leave a Reply