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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With