-3

I am not a javascript programmer, but I'm trying to hack an improvement to an existing running program.

In C, a common error is to define a variable within a function, then return it. Of course the variable vanishes off the stack when the function exits.

In javascript functions, I don't want to assign to a variable without a var, as that gives it global scope. So I say var foo = something;, then at the end of the function return foo.

This seems to work. Does it happen to work, or is it guaranteed to work? Is it the case that as javascript is garbage collected, the variable is now pointed at by the calling scope, which preserves it?

I've asked google, but either I'm not searching in the right place, the answer is too complicated for me to find, or the answer is so trivial it's not even mentioned.

It occurs to me that I could return an expression, avoiding naming it altogether. Is this more sensible?

Neil_UK
  • 1,043
  • 12
  • 25
  • The value of the variable, not the variable, is returned from the function. This works in C, too. – danh Dec 17 '18 at 15:10
  • If it did not work, we would have billions of applications across the net not functioning. – epascarello Dec 17 '18 at 15:11
  • Are you really asking if returning something from a function is guaranteed to return something from that function? Perhaps you have an example of something which is behaving in an unexpected way that has led to this otherwise strange question? – David Dec 17 '18 at 15:16
  • @David I'm really asking, *what* gets returned? Is it a pointer to valid memory, or to invalid memory? It seems to be valid, it seems to work. Why? When I return a variable I've declared to have local scope, when does the scope change to allow it to be referenced outside the function by the calling scope? – Neil_UK Dec 17 '18 at 15:21
  • @Neil_UK: Don't think of it as returning a *variable* from a function, think of it as returning a *value*. In the case of objects and whatnot that value may be simple a memory pointer to the object, but a value nonetheless. The "variable" is gone if it existed only within the scope of that function, but the "value" returned from the function can be assigned or used as needed. If nothing uses it, it falls out of scope and any memory cleanup will be handled. – David Dec 17 '18 at 15:52

1 Answers1

-1

As in C, A variable can be Value type, or Pointer type, but in javascript, all are Reference type, similar to Pointer type.

in your code, var only limit foo to be visible only in the containing function scope. something is an object bound to foo. but the object can be bound to any other variable too.

exudong
  • 366
  • 3
  • 13
  • here's a more accurate explain on `var` : > https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable-in-jav – exudong Dec 17 '18 at 15:44