Trying to understand - - TypeError: Cannot read property 'length' of undefined

I've ben trying to create a set of Yes/No type buttons which after a set timeout will default to "No" . . . I've managed to get it working but lost a lot of time to the following error: TypeError: Cannot read property 'length' of undefined

I've gotten around this but would like to understand why the error was being generated . . .

I have some test nodes to illustrate the issue:

Failing nodes:

[{"id":"acad1cef.8f8a3","type":"inject","z":"b7065b03.85e128","name":"enable","props":[{"p":"enabled","v":"true","vt":"bool"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payloadType":"str","x":310,"y":1240,"wires":[["9c356d1d.26da9"]]},{"id":"9c356d1d.26da9","type":"function","z":"b7065b03.85e128","name":"","func":"var print = { payload: msg.payload.length };\n\nprint = msg;\n\nreturn print;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":470,"y":1240,"wires":[["2db2248d.8c444c"]]},{"id":"2db2248d.8c444c","type":"debug","z":"b7065b03.85e128","name":"msg","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","statusVal":"","statusType":"auto","x":630,"y":1240,"wires":[]}]

Not failing nodes:

[{"id":"acad1cef.8f8a3","type":"inject","z":"b7065b03.85e128","name":"enable","props":[{"p":"payload"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"true","payloadType":"bool","x":310,"y":1240,"wires":[["9c356d1d.26da9"]]},{"id":"9c356d1d.26da9","type":"function","z":"b7065b03.85e128","name":"","func":"var print = { payload: msg.payload.length };\n\nprint = msg;\n\nreturn print;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":470,"y":1240,"wires":[["2db2248d.8c444c"]]},{"id":"2db2248d.8c444c","type":"debug","z":"b7065b03.85e128","name":"msg","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","statusVal":"","statusType":"auto","x":630,"y":1240,"wires":[]}]

The difference is that the failing node injects msg.enabled = true the not failing node injects msg.payload = true

For failing case the inject node does not send payload property (msg has only enabled property)
But in the following function you are trying to read payload.length. If property of object does not exist, you can't examine any part of it.
In this case you cant ask the length of msg.payload because msg does not have payload

1 Like

Ahh, I see . . . I assumed that;

var print = { payload: msg.payload.length },

was a kind of variable type or prototype, I didn't realise it would actually look for msg.payload.length

Thanks for the explanation. Every day is a school day :+1:

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