1

I want to know about more difference between global variable and local variable in javascript. I have heard one of my friend that global variable always stored in memory even function finish execution. But local variable store in memory when function start execution and removed from memory once it done with execution.

If this true how can I check memory consumption of function.

Jitender
  • 7,593
  • 30
  • 104
  • 210
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var – epascarello Jul 24 '15 at 17:47
  • in general, you really don't need to worry about JS memory consumption, unless low-ram symptoms appear, which is rare with well-written JS. usually, RAM problems are caused by coding mistakes or anti-patterns, or occasionally over-caching. in JS, other ram problems are much rarer than C programs written by someone of the same level of experience. – dandavis Jul 24 '15 at 18:25

1 Answers1

4

In JavaScript, variables are kept in memory as long as anything has a reference to the context in which they were created. In the case of global variables, since the global context has a reference to itself, they're always kept in memory.

That means local variables are kept in memory at least until the function they're in returns, at which point they're eligible to be reclaimed unless something still has a reference to the context in which they were created. In that case, they cannot be reclaimed, because something may still use them.

Here's an example of a local variable that can definitely be reclaimed when the function ends:

function foo(x) {
    var result = x * 2;
    return result;
}

And here's an example of a local variable that can't be reclaimed when the function returns, until or unless whatever called it releases its reference to the return value:

function makeCounter() {
    var n = 0;

    function count() {
        return n++;
    }

    return count;
}

Example use:

var c = makeCounter();
console.log(c()); // 0
console.log(c()); // 1
console.log(c()); // 2

In that case, since counter returns a function reference, and the function (count) has a reference to the context where n was created, n is not reclaimed as long as count exists. count is called a closure (it "closes over" the context of the call to makeCounter).

More:

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875