I know when setting an item in window.localStorage or window.sessionStorage, it needs to be first converted to a string. I'm just wondering... why was it designed this way? I tried googling it but I couldn't find any articles on why; mostly what I found were articles on how to set localStorage.
Why does localstorage have to be a string?
Asked Answered
The spec requires that values be stored as strings. It doesn't say why, but most likely it has to do with (ease of) serialization and deserialization, although one could argue that serialization/deserialization should have been an implementation detail. Now if only this design decision were documented somewhere... –
Shivers
I think you always get a string but you can save any value, you can use the developer tool console to see the log outputs:
<script type="text/javascript">
//Store
localStorage.setItem("integer", 1);
localStorage.setItem("float", 1.5);
localStorage.setItem("string", "Hello");
localStorage.setItem("array", [1, 2, 3, 4, 5]);
//Retrieve
console.log(localStorage.getItem("integer")==="1");
console.log(localStorage.getItem("float")==="1.5");
console.log(localStorage.getItem("string")==="Hello");
console.log(localStorage.getItem("array")==="1,2,3,4,5");
</script>
outputs:
Right but everything is converted to strings. If i try and set an object it gets converted to '[object Object]'. An array is turned into a comma seperated list as a string. Primitive data types are converted to strings. I CAN set non-strings into localStorage, but they are converted to strings. My question is.... why? –
Rosario
I am not sure but I think you can save a lot of work saving keys and values as string to be able to save different types of data, becuase that you can save an integer, a float, a string, an array or even a boolean or an object with the same functionality. Image a localStore with a: localStorage.set(Data Type)Item(...) Javascript is a weakly typed language. –
Spacetime
© 2022 - 2024 — McMap. All rights reserved.