Danaley
Danaley

Reputation: 803

Typescript functions that returns data

A general curious question. Let's say we have a Typescript function that returns an object data.

public abc(): data {
   let data: object = { ... }
   ...
   ...
   return data;
}

and we call the function with

abc();

But function abc() returns data. Is there memory leak or something since there is no variable to save the returned data like let saveThisData = abc();

Upvotes: 1

Views: 426

Answers (2)

Oscar Paz
Oscar Paz

Reputation: 18292

There is no memory leak. The next time the garbage collector executes, it'll see that there is no current reference (a variable in the global scope) from which you can reach what was defined as data, and so that object will be disposed.

In fact, if you assigned it to a constant:

const data = abc();

would be the same, provided you did this in a block or function. Once that block or function is out of scope, there will be no reference to that object and so, again, it will be disposed.

Of course, if you executed that statement in the global scope, then data would become a root reference, and so the object won't be disposed until the program finishes (when this happens, depends on the context of execution -- node, browser ...)

Upvotes: 1

Aaron Beall
Aaron Beall

Reputation: 52153

There's no memory leak. Because the return value of abc() is not referenced it will be garbage collected.

TypeScript doesn't change anything about this behavior from JavaScript, because TypeScript's return type is merely describing what is returned for the compile-time type checker.

Upvotes: 2

Related Questions