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);
CodePudding user response:
I don't understand your question, but I'll try my best to answer.
Basically, when you create a new Array()
, it adds two elements.
const arr = new Array(2);
console.log(arr); // Array of two values
When you add the extra three, it will just continue adding, instead of deleting the last three.
arr.push(1);
arr.push(2);
arr.push(3);
console.log(arr); // Array with five elements
To remove everything in the array, set length
to 0
.
arr.length = 0;
In summary, JavaScript will keep adding elements unless you explicitly delete them.