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

171
Vistas
JSON.stringify of an array returns a number after pushing more than one object

I am trying to add products to the cart in my website with localStorage, so I initialize an array and then push products into it. The problem is when I use JSON.parse() to push a product and then stringify it again with JSON.stringify() it returns a number instead of the array. This is the part of my code that throws an error:

let product = {
                id: i + 1,
                name: productNames[i].innerText,
                price: prices[i].innerHTML,
                img: imgs[i].src
            };

            if(localStorage.productsInCart) {
                let productsInLocalStorage = JSON.parse(localStorage.getItem("productsInCart") || "[]");
                console.log(productsInLocalStorage);
                let newArray = productsInLocalStorage.push(product);
                console.log(JSON.stringify(newArray));
                localStorage.productsInCart = JSON.stringify(newArray);
                numberOfProducts.innerHTML = parseInt(numberOfProducts.innerHTML, 10) + 1;

            } else {
                let productToStore = JSON.stringify([product]);
                localStorage.setItem("productsInCart", productToStore);
                numberOfProducts.style.display = "block";
                numberOfProducts.innerHTML = 1;
            };

And then in the console: enter image description here

That circled 2 is the console.log() of the JSON.stringify. I have been searching for detailed info about this but nothing seems to work.

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

0

The trouble is this line:

let newArray = productsInLocalStorage.push(product);

From the MDN Docs: The push() method adds one or more elements to the end of an array and returns the new length of the array. (emphasis mine)

You're assigning the length of the array to newArray.

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