Stupid Node-Red / Coding Question

This is a stupid coding question but for the life of me I cannot figure out what I am doing wrong here. I am trying to declare multiple arrays in a function on one line and no matter what I have tried only separating each individual declaration works. And to be clear I am not doing all three at the same time, that is just for display purposes otherwise obviously it’s going to tell you that you have duplicate array names.

//Define Test Arrays
// These are the three examples.  2 don't work 1 does. 

//DOESN'T WORK
var test1={}, test2={}, test3={}, test4={};  

//DOESN'T WORK
var test1,test2,test3,test4 = {};

//DOESN'T WORK
var test1=[],test2=[],test3=[],test4=[];

//WORKS
var test1 = {}
var test2 = {}
var test3 = {}
var test4 = {}

Do you have any more code in your function? Could it be causing an error?
What kind of error messages are you getting?

I tried your 2nd “DOESN’T WORK” code snippet in a Node-Red function (copied and pasted), and it worked just fine:
image

I’m am not an expert in Node-Red, but it certainly worked for me.

1 Like

I just made a test node too with the following and it works.
What error do you get?

var test1={'0':0},test2={'1':1};
var test3=[3],test4=[4];
msg.test1=test1;
msg.test2=test2;
msg.test3=test3;
msg.test4=test4;
return msg;
1 Like

Appreciate the help. Here is the full function. Nothing fancy just a hand full of tests. The error when using the other was undefined payload which would be coming from test1.payload assignment because it didn’t assign the array properly.

//Define Test Arrays
//var test1={}, test2={}, test3={}, test4={};


var test1 = {}
var test2 = {}
var test3 = {}
var test4 = {}

// Get states and put them into a global array
var states = global.get('homeassistant.homeAssistant.states');


// TEST1 Check Inside Temp
if (msg.data.attributes.current_temperature > 72) {
  test1.payload = true
  test1.topic = "ac_on1"
} else {
    msg.payload = false
    test1.topic = "ac_on1"
}

// TEST2 Check Hold Messages
if (global.get('ignore_ac')) {
    test2.payload = false
    test2.topic = "ac_on2"
} else {
    test2.payload = true
    test2.topic = "ac_on2"
}


// TEST3 Season
if (states["sensor.season"].state != "winter") {
    test3.payload = true
    test3.topic = "ac_on3"
} else {
    test3.payload = false
    test3.topic = "ac_on3"
}

// TEST4 Outside Temp
if (states["sensor.openweathermap_temperature"].state > 70) {
    test4.payload = true
    test4.topic = "ac_on4"
} else {
    test4.payload = false
    test4.topic = "ac_on4"
}


return [ test1, test2, test3, test4 ];

So does it make an error now?

It looks ok, although you have a msg.payload, that probably should be test1… Instead

1 Like

Good eye! I had it right but was troubleshooting the wrong thing. Tired eyes I guess. Was indeed the msg.payload that was triggering it.

This works now, thank you!

 var test1={}, test2={}, test3={}, test4={};