isn't localstorage as same as just a var | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

isn't localstorage as same as just a var

is var name='myname'=localstorage.setItem('name','myname') and when calling them we would use name or localstorage.getItem('name')

10th Sep 2020, 7:40 PM
Youssef Ashraf
Youssef Ashraf - avatar
7 Answers
+ 7
when declaring var name; its value is saved in RAM memory its value will be lost when closing or restarting the program. when you use localStorage.setItem ("key", "value") the data is stored locally. the correct way is: var name = localStorage.getItem ("name") || "noNamed"; function setName(newName){ localStorage.setItem("name", newName); name = newName; } if(name == "noNamed"){ setName("Luis"); } Now you can use var "name". @maf, in this case is not necessary to use JSON.parse, only use it when store a json: localStorage.set("user", JSON.stringify({ name: "luis", facoriteColor: "red" }) );
10th Sep 2020, 8:09 PM
CoffeeByte
CoffeeByte - avatar
+ 6
The difference is that if u set an item through localStorage.setItem(), it would remain there, even if u refresh your page, so its like a local database. And you have to parse data into JSON, when getting the item, so, JSON.parse(localStorage.getItem("name"))
10th Sep 2020, 7:44 PM
maf
maf - avatar
+ 6
Yeah i meant, when working with complex data, such as objects stuff. Then JSON.parse. you're right luis calderón
10th Sep 2020, 8:19 PM
maf
maf - avatar
+ 4
D_Stark it doesn't work in sololearn because playground is a web view
10th Sep 2020, 10:41 PM
CoffeeByte
CoffeeByte - avatar
+ 2
11th Sep 2020, 8:10 AM
D_Stark
D_Stark - avatar
+ 1
I used local storage to save game score it dosent seem to work here in sololearn not sure why.
10th Sep 2020, 9:59 PM
D_Stark
D_Stark - avatar
0
But also with the var when the page reloads the codes runs again including the var so it will be their Is the database backend related? Can you include an example
10th Sep 2020, 8:05 PM
Youssef Ashraf
Youssef Ashraf - avatar