Ayaz Ujjan Ayaz Ujjan - 1 year ago 83
Javascript Question

local storage Overwriting issue

i have been working on quiz app where i am only allowed to use javaScript. the app works like i ask user to chose username and i save it in variable and he/she starts answering and the score gets higher and higher and being saved in score variable as well. later on once the game finishes i am printing the message and have to present the 5 top score users. for that purpose i am using local storage, the problem is when i save the data it works fine but when i restart or play again the data is being overwritten. for example first user name being replaced with newer player. my code for saving the data is ;

var obj = convertUserAndScore(user, score);
var players = new Array;

players.sort(function(a, b){
return a.score - b.score;


localStorage.setItem("players", players);

function convertUserAndScore(user, score) {

return { "usename": user , "score": score};

Answer Source

Several problems.

First you always initialize an empty array...and never get the stored data from localStorage

Next you take that empty array and store it in localStorage right away. This would definitely overwrite any other time you actually store an array with length

Third you are stringifying the elements in array when you need to stringify the whole array

Lets start with page load:

var localData = localStorage.getItem("players");
// if defined then parse stored data or use empty array
var players = localData ? JSON.parse(localData ) : [];

Now when you do something to change array you need to stringify the whole thing

var somObj= //...
localStorage.setItem("players", JSON.stringify(players));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download