Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is an array stored in memory in Javascript? [closed]

We know objects are stored in the heap area.

Suppose we are inside a function block where we declare:

var a=[1,2] 

And

var b=new Array(1,2)

Will both the array objects be stored on the heap or will a have space in the stack area and will b be on the heap?

like image 684
Suraj Prakash Joshi Avatar asked May 09 '26 13:05

Suraj Prakash Joshi


1 Answers

It makes no difference to where the array is stored whether you create it with an array initializer (aka "array literal", [1, 2]) or the Array constructor (new Array(1, 2)).

Re where the array is stored:

It's up to the JavaScript engine implementation, and so may vary from implementation to implementation.

Some advanced engines use escape analysis to determine where to allocate objects, including arrays, which means they may be allocated on the stack or may be allocated on the heap depending on whether the engine sees that they are local to the function or they escape the function (e.g., by being returned, or assigned to a variable the function closes over, etc.).


Side note: There's almost never any reason to use new Array.

like image 183
T.J. Crowder Avatar answered May 12 '26 03:05

T.J. Crowder