0

I have a function a where there is a function b that references foo in its closure.

class Foo {}

function a() {
  const foo = new Foo()
   const b = () => {
        foo // referencing `foo`
    }
    b()
};

a() // no memory leaks

after I executed a, there are no memory leaks for Foo.

I also tweaked it slightly. Still, no memory leaks for the following examples.

class Foo {}

function a() {
  const foo = new Foo()
   const b = () => {
        if(foo === 'foo') {
            
        }
    }
    b()
};
a() // no memory leaks

class Foo {}

function a() {
  const foo = new Foo()
   const b = () => {
        console.log(foo.lol)
    }
    b()
};
a() // no memory leaks

But as soon as I logged out foo, it causes memory leaks.

class Foo {}

function a() {
  const foo = new Foo()
   const b = () => {
        console.log(foo)
    }
    b()
};
a() // memory leaks

enter image description here

My question is why console.log(fii) leaks but referencing foo in other ways or log out its property console.log(foo.lol)

I tested these in Chrome 103 DevTool console.

Joji
  • 4,703
  • 7
  • 41
  • 86
  • what makes you think there's leaks? a memory leak is a very specific issue - you have not demonstrated anything more than results of javascript engine code optimisation in my opinion. In the last example, the engine needs to keep a ref to `Foo`, since it is being used on the console - all other code is so trivial, class Foo can be optimised away - it literally plays no part in anything - at least, that's my opinion – Jaromanda X Jul 17 '22 at 06:07
  • It's not a leak, it's a use of the object. Used objects naturally can't be freed. See the duped question for more details. – jmrk Jul 17 '22 at 12:15
  • @jmrk but isn't `foo` also used objects in any other examples, e.g. `if(foo === 'foo')` and ` console.log(foo.lol)`? why is that only `console.log(foo)` would prevent it from being collected? – Joji Jul 17 '22 at 17:25
  • `console.log(foo)` hands a pointer to `foo` to the console. The console keeps it alive, so that you can inspect it. The closure `b` has nothing to do with it. – jmrk Jul 17 '22 at 18:27
  • interesting... but `console.log(foo.lol)` doesn't point to `foo` and it doesn't keep `foo` alive? – Joji Jul 17 '22 at 18:48

0 Answers0