Where to use let and where to use var in a function node?

when would you recommend to use the let versa the var statement ?
What is the scope of a function node?

Have a look at the code. If I replace all var with let I get an "already declared error"

var nodes = flow.get("nodes");

var node = nodes.find(n => n.nodeid == msg.payload.nodeid);

var value = node.values.find(v => v.value_id == msg.payload.value.value_id);

value.value = msg.payload.value.value;

msg.payload = value;
msg.topic = "value_changed";

return msg;

you get error as node is already defined (e.g. node.send() is a function in the node object already defined in the function vm)

The fact this error occurs when you use let is a good demonstration of how let and const can help you find bugs.

EDIT...
It is definitely preferable to use let and const over var.

1 Like

I agree, don't use var unless you have a good reason.

1 Like

And here is an example and explanation, something to think about (I definitely felt I sometimes needed var)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#:~:text=let%20allows%20you%20to%20declare,function%20regardless%20of%20block%20scope.

Should that link have taken me to a specific example where var is required? It didn't.

thanks for your help.
this is how it works:

let nodes = flow.get("nodes");

let actual_node = nodes.find(n => n.nodeid == msg.payload.nodeid);

let value = actual_node.values.find(v => v.value_id == msg.payload.value.value_id);

value.value = msg.payload.value.value;

msg.payload = value;
msg.topic = "value_changed";

return msg;

Not really. But a better explanation of the differences

I think those can all be const as you only assign each reference once. You might think that value cannot be const as you write to value.value, but the variable value is, effectively, a pointer to a structure in memory, and that pointer is not changed when changing the contents of the object, so writing to value.value does not change the variable itself.
In theory using const may allow the interpreter/compiler to generate more efficient code, but whether that is actually the case in the node-red environment I don't know. It does stop one accidentally overwriting a variable that should not be overwritten.

I believe in practise it's more about the latter. I assume most function nodes are quite short so it might not be very likely to catch any errors. But I tend to also use const when possible out of the habit of it being the recommended practise for bigger code bases which I encounter daily at work.

1 Like

const everything, unless you have to use let. only use var if you travel back in time. :nerd_face:

3 Likes