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

170
Views
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 answers
Answer question

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 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!