Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

110
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda