If I have an array of 1000 elements and I set the array length to 10, where the other element will go? Will that cause a memory leak?
-
You cannot update an array length after its created. You can remove items from it which will update its length. – Steve Tomlin Aug 01 '21 at 12:16
-
3@SteveTomlin Sure you can set the length – Bergi Aug 01 '21 at 12:23
-
@SteveTomlin [uhhh, what?](https://jsbin.com/liqawuzecu/edit?js,console) – VLAZ Aug 01 '21 at 12:42
4 Answers
where the other element will go?
The properties 10
to 999
will get deleted when you assign .length = 10
.
Setting .length = 0
is a well-known solution for emptying an array.
Will that cause a memory leak?
No, they will get garbage-collected normally.

- 630,263
- 148
- 957
- 1,375
The ECMAScript specs are saying that the elements are deleted
:
Reducing the value of the "length" property has the side-effect of deleting own array elements whose array index is between the old and new length values.
Also, ArraySetLength is specifying that a Delete
is performed for whose numeric value is greater than or equal to newLen, in descending numeric index order
So no - there will be no memory leak if you reduce the length of an array.

- 339
- 2
- 5
Using []
or new Array(10000)
will both create Arrays with exactly the same memory footprint. Just the length has a different initial value.
JavaScript is different from other languages, where an array of size n will have n storage spaces reserved for the elements.

- 18,263
- 7
- 55
- 75

- 260
- 3
- 11
if array length is set to smaller value then other values gets removed/deleted from the array.
lets say
let arr = [1,2,3];
then if you set
arr.length = 1;
then the arr
will have only [1]
, other elements gets removed from the array.

- 5,792
- 2
- 28
- 41