OK, so I have created an HTML5 canvas game that uses localStorage. I have localStorage working perfectly but I’m not sure that it follows the correct standards, or if it is completely fine the way that I have written it.
//check if storage is set already, if not set the variable
function checkLocalStorage(){
if (localStorage.timesPlayed){
timesPlayed = Number(localStorage.timesPlayed);
}
else{
timesPlayed = 0;
}
}
//code snippet to increase my variable
timesPlayed += 1;
//code snippet to set the localStorage
localStorage.timesPlayed = timesPlayed;
This works perfectly!? But from what I have read, i should be using localStorage.getItem and localStorage.setItem?
Should I change the way I write localStorage??
This is just the link to the website where I learned this way to access localStorage
http://hacks.mozilla.org/2009/06/localstorage/
It works, and it probably won’t break, but I’d still try to cast things in the correct type when using localStorage.
getItemandsetItemare the preferred ways of doing things, but the thing that jumped out at me was that your methods of getting and setting the value won’t work for any type but a number, which means you have to code cautiously if you’re using a lot of localStorage.You’re sending a number to localStorage, where it’s converted to a string. This can get you into a lot of trouble when dealing with booleans, for example:
Arrays and objects get ugly too:
In other words, what you have works, but it’s a good habit to do things correctly and consistently from the start, as it will simplify debugging later. The correct way — which works with strings, numbers, arrays, objects — is this: