2 points · by shivajikobardan · 3y ago · 4 comments
It's the project that I'm trying to understand. It's the javascript that I'm concerned.
I tweaked the Javascript code to this:
var count = 0;
function increaseCounter() {
count += 1;
window.localStorage.setItem("count", count);
document.getElementById("score").innerHTML = count;
}
function decreaseCounter() {
count -= 1;
window.localStorage.setItem("count", count);
document.getElementById("score").innerHTML = count;
}
function clearCounter() {
window.localStorage.clear();
document.getElementById("score").innerHTML = "";
}
This is what I've tweakedhttps://imgur.com/a/iKpHm0N
I don't get the need for the commented line in this case. Why're we using it? I by now of course know it's needed. But can't understand why.
I'm facing a problem
1) I increase count to 13.
2) I clear localstorage.
3) I click decrease score. Now, score starts to decrease from 12. So, storage isn't being cleared right?
Why's it like that?
Dry run in the above code seems fine.
1) Initial count=0
2) Click increase count button
3) count=1
4) Again click increase count button
5) count=2
6) Now I clear Counter, count should be 0.
7) I click decrease counter
8) count=-1
and so on.
What am I missing here?
function decreaseCounter() {
let count = parseInt(window.localStorage.getItem("count"));
count = count - 1;
window.localStorage.setItem("count", count);
}
all values stored in localStorage and sessionStorage are strings, so you have to convert to a number. You'd probably want a try/catch in there somewhere if count is not yet defined in the store, unless that possibility is dealt with elsewhere in your code. Also, the counter might need to check for boundary conditions (e.g. it can be negative here). But that is beyond the scope of your question.This is my project for localStorage.
var count = 0;
function increaseCounter() {
// var count = Number(window.localStorage.getItem("count"));
count += 1;
window.localStorage.setItem("count", count);
document.getElementById("score").innerHTML = count;
}
function decreaseCounter() {
// var count = Number(window.localStorage.getItem("count"));
count -= 1;
window.localStorage.setItem("count", count);
document.getElementById("score").innerHTML = count;
}
function clearCounter() {
window.localStorage.clear();
count = 0;
document.getElementById("score").innerHTML = "";
}
This code works now. But is there a point of using localstorage if I'm going to do like this? My goal for asking the question was to understand the first line.[CODE] // var count = Number(window.localStorage.getItem("count"));[/CODE]
I didn't get what we did here and why we did here.