Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
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);

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!