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

124
Vistas
Potentioal memory leak with spread operator?

I'm just wondering if the following code snippet is a potential memory leak.

let arrOfObj = [
    { a: 0, b: 0 }
]

const copy = [ ...arrOfObj ]
copy[0].a = 5;
console.log(arrOfObj)
// [ { a: 5, b: 0 } ]
console.log(copy)
// [ { a: 5, b: 0 } ]

arrOfObj = []
console.log(arrOfObj)
// []
console.log(copy)
// [ { a: 5, b: 0 } ]

The spread operator will only do a shallow copy, so the object inside the array would be a reference. But where did javascript get the values in the last log? Will they garbage collected as I empty the array?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

No, there is no memory leak. Breaking down the steps for better explanation:

  1. const copy = [...arrOfObj] : allocates space in memory heap and assign it to copy variable. Since, spread performs shallow copy, the object reference is still same inside of the array.
  2. copy[0].a = 5; : updates the value of the object inside of copy array. Since, the reference to object is same for both copy and arrOfObj, it is reflected in both the arrays.
  3. arrOfObj = [] : allocates space in memory heap for [] and assigns it to arrOfObj variable. This does not imply that copy loses its reference to the array you created earlier. copy still points to the older memory reference. Hence, copy prints out the older array containing object, and arrOfObj prints empty array.

To ellaborate more on this, even if you do the following, copy would still point to older memory reference :

let arrOfObj = [
    { a: 0, b: 0 }
]

// instead of spread, assign it directly 
const copy = arrOfObj;
copy[0].a = 5;
console.log(arrOfObj)
// [ { a: 5, b: 0 } ]
console.log(copy)
// [ { a: 5, b: 0 } ]

// assign empty array to 'arrOfObj'
arrOfObj = []
console.log(arrOfObj)
// []
console.log(copy)
// [ { a: 5, b: 0 } ] => still prints the array

Also, the older value of arrOfObj "may" get garbage collected (depends on JS engine optimisations)

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