1

I thought that variables were destroyed as soon as their context did not exist anymore:

function foo () {
    let bar = "something"
    return bar
}

Like in this example, I thought that bar was destroyed as soon as the function got executed.

But now, I discovered that you can write this in Javascript:

function foo () {
  let bar = "something"
  return {
    print () {
        console.log(bar)
    }
  }
}

let f = foo()

f.print();

This code prints "something". So I wonder now how javascript handles its memory. Why bar does not get destroyed at the end of the function?

Now, if I write something like:

function foo () {
  let bar = "something"
  let hugeVar = _.range(1,1000*1000*1000*1000) // A huge array
  return {
    print () {
        console.log(bar)
    }
  }
}

Is hugeVar still in the memory? How Javascript decides what to keep and what not to keep?

Hammerbot
  • 15,696
  • 9
  • 61
  • 103
  • A variable is never destroy in Javascript: you can not destroy willingly a variable. A variable will be just increase or destroy when the browser think you do not need anymore the variable. Refer to this link: https://stackoverflow.com/questions/16963066/how-to-delete-a-variable – SphynxTech Oct 22 '17 at 11:36
  • 1
    @GuyT: Variables don't get garbage-collected, only objects. Plus, the standard doesn't even guarantee *that*. The standard only specifies when an object is reachable or not. What to do with unreachable objects is left to the implementation. The vast majority will *not* collect an object's memory as soon as it becomes unreachable, but rather wait until there is a large number of unreachable objects and collect them in a single batch. – Jörg W Mittag Oct 22 '17 at 11:39
  • 1
    How memory is handled in JavaScript has nothing to do with closures. Incorrect duplicate selected. – Keith Oct 22 '17 at 11:45
  • The last part of the question is a simplified version of [what i asked some time ago](https://stackoverflow.com/questions/38838071/closure-memory-leak-of-unused-variables). You can find your answer there. – ASDFGerte Oct 22 '17 at 11:49
  • @JörgWMittag A variable is stored somewhere in memory - as part of a scope (lexical environment) - and that will get garbage-collected like everything else. It's just not a JS object but a native one. – Bergi Oct 22 '17 at 12:22

2 Answers2

0

It is called closure. Functions will remember those references to variables in external scopes. Read about it for more information.

0

The code you're providing it's an example of closures.

A closure is a stack frame which is allocated when a function starts its execution, and not freed after the function returns (as if a stack frame were allocated on the heap rather than the stack!)

A closure remembers the parent scope.

JJJ
  • 32,902
  • 20
  • 89
  • 102
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128