0

So I've read about the stack and heap recently and how are they managed in runtime, but there's a case that's been bothering me, since I have a specific usecase in my test suites.

For example,

function foo(myOjb) {
   myObj.fooMethod();

}

In the code above, I'm creating a reference to an already existing object instance, which in my particular case is responsible for creating http interceptors. I run this type of functions several times within a single test, since I'm delegating the logic for creating those interceptors to another functions, instead of writing them line by line in my suites to avoid too much boilerplate, repetition and improve readability. So my question is - are all of those resources freed when each function exits (returns undefined)? I'm asking this because the object itself still exists in memory and I became afraid that I'm using up too many resources with such a reckless approach.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
pq89
  • 141
  • 6
  • A new *stack frame* is created when you call a function and it's cleared when the function exists. So, you don't need to be thinking too hard about this. EDIT: I partially wrote about the stack [here](https://stackoverflow.com/questions/39459236/understanding-event-queue-and-call-stack-in-javascript/39459913#39459913) - see if that helps. – VLAZ May 21 '19 at 06:29

1 Answers1

0

Short answer to the question the title is - YES.

Let the function arguments be object references or primitive variables, they last in the stack only until the function is being executed.

One major effect of the above mechanism is that, when the arguments are object references, only the reference is poped out from the stack. The real object you are referencing still lives in the memory until the JS garbage collection process determines that the memory is not referenced anymore by any variable.

This is solely automatic and will manage to clean the memory up for new allocations regardless of how many objects you create and abandon them by way of removing the references.

function testObj(myObj) {

    return typeof myObj === 'object'

}

var o = {}

testObj(o)   //The object o will still live after this call, because variable o points to it even after the function exists.



test({}) // Don't worry about this improvised  object. There won't be any references to it after the function call

Here is an article which you can have a closer look at.

Charlie
  • 22,886
  • 11
  • 59
  • 90