Kunok Kunok - 4 months ago 12
Javascript Question

Do variables declared inside callback functions remain in memory or are they destroyed upon end of callback execution?

I have this code snippet; It basically connects to mongo database and goes through documents. On each iteration it searches for messages array of objects. It creates variable of messages, and then loops through it. Does declared variable (

var msg
) inside callback function remain in memory or is it destroyed upon end of callback function execution? Would there be any difference if
var msg
was actually declared as
let msg
? Is there a way to discard whole scope from the memory?

MongoClient.connect(mongoUrl, (err, db) => {
var collection_data = db.collection('threadContents').find();
collection_data.on('data', (doc) => {
var msg = doc.messages;
for (var variable in msg) {


In theory - yes.
In practice - it's not that simple...

In your example, var msg does not "leak" outside of it's original scope, so it will most likely get destroyed when callback finishes it's job.
One thing to note - the destruction of this object doesn't have to happen immediately - JS Engines are mostly Garbage Collected, so this piece of memory can stay on the stack for some time, but it won't be reachable anymore.

If you would declare this variable in outer scope, it could possibly stay in the memory if that scope stayed in memory (so, other pieces of code could access that variable). You can read about this behavior in Closures section at MDN.

Another thing to note is usage of console.log. In general, non-primitive values (like Objects or Arrays, which actually are "special" objects), will be accessible by reference, not by value. Therefore, if your var msg is a non-primitive, it will most likely persist in the memory until you clear your console. Primitive values would be copied, so strictly speaking they would still persist in the memory, but probably in another place in the memory (although JIT engines could probably try to optimize that and don't copy the memory if it's not necessary).