'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);


Solution 1:[1]

You are missing quotes around users :

if (localStorage.getItem("users") === null) {

Solution 2:[2]

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);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tom
Solution 2 sid