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

101
Views
Im trying to create an array of user Objects in local Storage using vanilla JS

I'm creating a simple quiz app and i would like to store an object of each user and their score in an array stored in local Storage. The problem is every time I initiate the function instead of adding a new object to the array the existing object values are changed instead

//JS code

function storeUsers(userObject) {
    if (localStorage.getItem(users) === null) {
        users = []
    } else {
        users = JSON.parse(localStorage.getItem(users))
    }

     const userScoreTemplate = function (usersName, usersScore) {
            this.user = usersName;
            this.score = usersScore;
        }

        newUser = new userScoreTemplate(userName, score);
        


    users.push(userObject);
    localStorage.setItem("users", JSON.stringify(users))


}

storeUsers(newUser);
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Correct reference should solve it, the arguments passed to function(usersName, usersScore) will not be accessible outside the function, thats why your code doesn't work. You're passing parameter to the storeUsers function so that should be used whereever needed.

newUser = new userScoreTemplate(userObject.userName, userObject.score);
about 4 years ago · Juan Pablo Isaza Report

0

You miss quotes in localStorage.getItem.

I also recommend you separate the functionality of your function like below:

class UserScoreTemplate {
    constructor(userName, userScore) {
        this.user = userName;
        this.score = userScore;
    }
}

function storeUsers(userObject) {
    let users = [];

    if (localStorage.getItem("users")) {
        users = JSON.parse(localStorage.getItem("users"));
    }

    users.push(userObject);
    localStorage.setItem("users", JSON.stringify(users));
}

const newUser = new UserScoreTemplate("John", "Doe");

storeUsers(newUser);
about 4 years ago · Juan Pablo Isaza Report

0

You are missing quotes around users :

if (localStorage.getItem("users") === null) {
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!