I wonder whether it is safe to use let in this scenario:
function test() {
let result = 0;
result++;
return result;
}
Yes, it is perfectly safe and it is the expected way to declare a local variable that you later want to return as the value of the function. Because Javascript is a garbage collected language, the local variable can safely contain any type of value. It can have a simple primitive like you show, or it can even contain an object like this:
function test() {
let result = {cnt: 0};
result.cnt++;
return result;
}
let obj = test();
console.log(obj); // shows {cnt: 1}
This is safe because though you are returning an object that was declared within the scope of a function and that function scope will go out of scope when the function returns, because Javascript is a garbage-collected language, the object will separately live on in whatever the return value of your function is assigned to outside of the function scope.
To piggy back on the comments posted above.
Const - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const is a great way to let yourself as well as other people who are reading your code know that 'this variable wont be reassigned or modified.'
Let - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let lets people know that this variable will most likely get reassigned or modified.
Use of let in your case is perfectly okay!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With