Pm code checking array for undefined element

GET response brings back a certain number of elements.
Have an array, sized with expected number of elements anticipated.
So we walk through the GET response (for-loop), checking each element in the GET response for specific data depending on data in that element of the response (if field1=“xy” then check this value and that value) and putting the ‘key’ value (field1) into the array allocated earlier.
Then want to check the array to ensure the keys received in the GET response were the expected ones…and there’s the issue:
I have an array of size 2, and first array element has a value and second if undefined because the related event didn’t come in the GET response.

Q: How can you check an array element for an ‘undefined’ value?

Hi @ksully

Maybe this would help?

let myVar1;

if(myVar1 === undefined){
    console.log("myVar1 is undefined")
    console.log("myVar1 is defined")


let myVar2 = 1;

if(myVar2 === undefined){
    console.log("myVar2 is undefined")
    console.log("myVar2 is defined")


very cool, can you tell me how to convert that to a pm.expect statement?
this doesn’t work, etc. pm.expect(eventFound[i] != undefined);

You could do something like this;

pm.test("myVar1 is defined", function () {

pm.test("myVar2 is defined", function () {


I’m working with an array here, so it doesn’t like that syntax…
gives: TypeError: Cannot read properties of undefined (reading ‘be’)

I’d need a screenshot or something, there isn’t enough information to work with there…

Could you show your test tab code and response?

can recreate it (can’t share the real thing:, see below:
an array is created:
var eventFound = new Array(2);
And filled by a for loop, processing each received event, but not all slots in the array will be filled if the number of expected events are not received (hence the undefined entries being left).
for(var i = 0; i < 2; i++) {
eventFound[i] = “SomeEventName”;
Then we loop through that same array, looking for undefined entries (if any):
for(var i = 0; i < eventFound.length; i++) {
pm.expect((eventFound[i])“undefined”)); //not working…

It’s hard to work it out without seeing the actual code etc.

But assuming your array values are strings then try this;

let count = 0;

for (i = 0; i < myArray.length; i++) {
  //Tests to PASS
  try {
  catch (e) {
    pm.test("Check if index " + [i] + " is undefined", () => {
      throw new Error("Value is undefined")
    }), count++;


1 Like

Thanks much, and sorry I couldn’t share the real code…
The earlier suggestion:
pm.expect(eventFound[i])"undefined","undefined event found");
actually does work, I had an IF catching it above and calling so it wasn’t getting there…
I’m sure the try/catch would probaby work as well. Thanks again!

1 Like