You can return a value from a function, of course:
function blah() { var a=1; return a; }
But I suppose that is not quite what you had in mind. Since calling a function creates a closure in local variables, it is usually not possible to change values โโafter creating a closure.
Objects are slightly different because they are reference values.
function blah1(v) { setInterval(function() { console.log("blah1 "+v); }, 500); } function blah2(v) { setInterval(function() { console.log("blah2 "+va); }, 500); } var a = 1; var b = {a: 1}; blah1(a); blah2(b); setInterval(function() { a++; }, 2000); setInterval(function() { b.a++; }, 2000);
If you run this in an environment with a console object, you will see that the value reported in blah2 changes after 2 seconds, but blah1 just continues to use the same value for v.
source share