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

105
Views
Under what circumstances would it be useful to change a javascript array's length, without actually adding a new element

In this question, I figured out that my problem was because I had accidentally incremented the Array.Prototype.length property using ++

What I'm wondering is why length isn't a read-only property of Arrays? I see that it isn't an oversight in the language's design, because MDN says specifically it can "SET or return" the length of an array. I'm just wondering why I'm able to screw up in that particular way? What kind of use case would merit being able to change the length of an array without changing the number of elements it contains?

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

0

I found this interesting article from JavaScriptTutotorial.net that explains why you might use this.

Empty an array

If you set length to zero, the array will be empty:

const fruits = ['Apple', 'Orange', 'Strawberry'];
fruits.length = 0;

console.log(fruits); // []

Remove elements

If you set the length property of an array to a value that is lower than the highest index, all the elements whose index is greater than or equal to the new length are removed.

The following example changes the length property of the fruits array to two, which removes the third element from the array:

const fruits = ['Apple', 'Orange', 'Strawberry'];
fruits.length = 2;

console.log(fruits); // [ 'Apple', 'Orange' ]

Make array sparse

If you set the length property of an array to a value that is higher than the highest index, the array will be spare. For example:

const fruits = ['Apple', 'Orange', 'Strawberry'];
fruits.length = 5;

console.log(fruits); // [ 'Apple', 'Orange', 'Strawberry', <2 empty items> ]
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!