Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading