'Why doesn't javascript reset the cursor back to zero after allocating a size to the array
Taken an array with given size, when we try to push the elements into it, javascript pushes the elements post the allocated size. Shouldn't javascript reset the cursor back to zero and push the elements from the 0th index onwards?
const arr = new Array(2);
arr.push(1);
arr.push(2);
arr.push(3);
console.log(arr.length);
Solution 1:[1]
When you create a new Array(2)
, it adds two elements, both with a value of undefined
.
const arr = new Array(2);
console.log(arr); // [undefined, undefined]
When you add the extra three, it will just continue adding to the array, instead of deleting the last three.
const arr = new Array(2);
arr.push(1);
arr.push(2);
arr.push(3);
console.log(arr); // [undefined, undefined, 1, 2, 3]
If you, however, want to remove everything from the array, you can set length
to 0
.
const arr = new Array(2);
arr.length = 0;
console.log(arr); // []
In summary, JavaScript will keep adding elements unless you explicitly delete them.
Note: Don't use new Array()
. Instead, use an empty array ([]
). This answer used the Array()
constructor to match with the question.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Community |