For if statement in Function Block, variable remains local

Please review this code:

let senState_msg;
if (msg.payload==="On") {
let senState_msg={payload:"Sys08: ASE"};
} else {
let senState_msg={payload:"Sys07: SSD"};
}

return senState_msg;

I've declared the variable senState_msg prior to the if-block, but the variable of the same name within the if-block remains local. How do I get the value set in the if-block outside?

Chatted with @xytsrm he found an answer and I thought it was a good question for future readers so opened to allow a response.

here is the chat

Me
Hi, That is a good question. I take it you figured out not to declare let again inside the if block.

xytsrm
Yes, exactly. I don't use Java script too often, I'm far more familiar with Python where there are no explicit declarations. Also, I learned that if you want a variable to be global outside the if-block you need to declare it before the if-block. There was an archaic programming language that I used decades ago where you needed to use "let" all the time, for declarations & assignments; I think that was blinding me to the "let" statements in the if-block.

The funny thing is I summited that code sample to ChatGPT, before I made the declaration prior to the if-block. ChatGPT said the code looked ok, but I needed to make the declaration before the if-block. BUT, then it reprinted my code WITHOUT the "let" in the if-block. Can you believe I still missed the removal of the "let"; it never explicitly said you need to remove the "let" - lol.

Regarding leaving the question on the forum as a "learning experience" you right I probably should have, but I was so embarrassed by what I came to see as an obvious error, I hastily deleted it; I'll consider un-deleting it.

Me
If you want a global var declare it with var name;

Mistakes are easy to overlook we have all been there

This is a great community and I would not worry about embarrasment, there are no stupid questions when learning.

xytsrm
Thanks for the encouragement - lol

Interestingly, I found the either let, or var works, but you're right var is preferred. I had tried the 'var' but it made no difference to the error, but that was before I realized the real error; the 'let' in the if-block.

Me
var is global and will be available any where
let is confined in the { } block only or global if defined outside any { }

preference
is
const
let
var
in that order
const means the var will not change, object defined const must always be an object but you can redefine the properties.

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