Help if not defined variable is accessed

Yeah, it is probably easy to do, but for now it escapes me how to do it.

This is the code on a Function node:

var m = msg.month;

m = parseInt(m);

var x = msg.table[m];

msg.payload = x;

return msg;

If msg.table isn't an array, it throws an error.

How do I get around it and use a default value?

Thanks.

1 Like

Ok, this seems to work:

var m = msg.month;

m = parseInt(m);
var x;

if (msg.table != undefined)
{
    x = msg.table[m];
} else
{
    x = 22;
}

msg.payload = x;

return msg;

If it isn't defined I get back 22.

But is there a neater way of doing it?

For testing an array you can use if(Array.isArray(msg.payload) && msg.payload.length)
This ensures the variable is an array && that it has 1 or more items.

Sorry, I don't understand that.

I can only resolve it to:

if(msg.table.isArray()

msg.payload isn't part of the equation as I see it.

msg.month will be set. That is set by the upstream node to set the month value for this month.

It is just the array msg.table which may not be set/defined and that is generated upstream too.

I may look at how it is set and do a condition there. But at the end of the day, it needs to be done somewhere and due to recent observations here is as good a place as any to check/test for it being set and if not, set a default value.
Less nodes needed/used.

I misread. But essentially is the same.

if(Array.isArray(msg.table) && msg.table.length)

The point is that testing for a variable being not undefined does not mean it is an array nor that it has 1 or more elements.

I.e. avoid bugs.

Yeah, thanks.

Alas (as you may have noticed/seen) I've been away from NR for a long time.
(Other things happening)

I really do need to keep on top of checking if things I get are (or not) defined and deal with it better than throwing an error.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.