Why are Objects with Value of 0 Treated Differently?

Working with an ESP32 Cam, settings can be sent to the camera via MQTT such as
cmnd/esp32cam/WcBrightness followed by one of 5 number values -2, -1, 0, 1, 2

Feedback by subscribing to stat/esp32cam/RESULT will then show: stat/esp32cam/RESULT = {"WCBrightness":-1}

Can also request ALL setting values that will show: stat/esp32cat/RESULT = {"WC":{"Stream":1,"Resolution":9,"Mirror":0,"Flip":0,"Saturation":1,"Brightness":-1,

I parse the "RESULT" feedback and if a single object is returned I update my deviceObject and then request and update for all settings.

It all works except when I issue the setting command with value of 0. The camera makes the setting adjustment and returns "RESULT" ... 0, but the flow will not go on to request the UPDATE.

Attached is my best attempt to simulate what I have going on. Aside from my poor coding, inject the different values and you will see what I am talking about.

Why is 0 being treated differently?
ESPcamSetting.json (10.2 KB)

Not checked you flow but this usually happens with JavaScript when someone makes an assumption in a logic check such as an if statement. This comes down to JavaScript being an untyped language where true/false is assumed from truthy/falsy data such as values 0 an -1.

As with most of my "issues", this is most likely self-inflicted. I recently ran across object?.property thinking it could take the place of object.hasOwnProperty("property"))

In my example flow, function 7 node, when I replaced this:

if(w?.MySetting)  {
    od.MySetting = w.MySetting;
    msg.payload = "?";
}

with this

if(w.hasOwnProperty("MySetting"))  {
    od.MySetting = w.MySetting;
    msg.payload = "?";
}

The flow works as I would expect. I can't explain why it works, but it now does.

if(w?.MySetting)  {

Will fail for all of these...

w.MySetting = 0
w.MySetting = false
w.MySetting = null
w.MySetting = undefined

Read up on falsey values: Falsy - MDN Web Docs Glossary: Definitions of Web-related terms | MDN

To work with "good numbers" use...

if(typeof w?.MySetting === 'number')  {

@Steve-Mcl, thank you for pointing this out. In my case w.MySetting = 0 is what was causing my issue. While I thought it was just a check to see if an object 'MySetting' is present, I did not realize it also pulls in the value of the Object and when 0 is a falsey.

My bad for thinking w?.MySetting is the same as w.hasOwnProperty("MySetting").

1 Like

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