Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it safe to use let for a variable which return result? [closed]

I wonder whether it is safe to use let in this scenario:

function test() {
  let result = 0;
  result++;
  return result;
}
like image 982
longlifelearner Avatar asked Feb 15 '17 22:02

longlifelearner


2 Answers

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.

like image 51
jfriend00 Avatar answered Nov 20 '22 01:11

jfriend00


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!

like image 32
Matt Fernandez Avatar answered Nov 20 '22 01:11

Matt Fernandez