Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript closures on heap or stack?

Where does JavaScript (according to the standard) store closures: heap or stack?
Is there a third explicit place for closures?

like image 399
Michael Dorner Avatar asked Jun 06 '13 10:06

Michael Dorner


People also ask

Where are closures stored in JavaScript?

It is created and destroyed every time the function is executed, and it cannot be accessed by any code outside the function.

Where are closures stored in memory?

So. With this in mind, the answer is that variables in a closure are stored in the stack and heap.

How does closures work in JavaScript?

A Closure is a combination of a function enclosed with references to its surrounding state (the lexical environment). In JavaScript, closures are created every time a function is created at run time. In other words, a closure is just a fancy name for a function that remembers the external things used inside it.


1 Answers

In the end it is an implementation detail of the runtime. See Phoenix link

As to implementations, for storing local variables after the context is destroyed, the stack-based implementation is not fit any more (because it contradicts the definition of stack-based structure). Therefore in this case closured data of the parent context are saved in the dynamic memory allocation (in the “heap”, i.e. heap-based implementations), with using a garbage collector (GC) and references counting. Such systems are less effective by speed than stack-based systems. However, implementations may always optimize it: at parsing stage to find out, whether free variables are used in function, and depending on this decide — to place the data in the stack or in the “heap”.

like image 61
aggsol Avatar answered Oct 02 '22 22:10

aggsol