JavaScript Local Storage Techniques

Local storage or session is part of web storage; it is an elegant technique for storing data. This way is better than cookies and another traditional way; Local storage looks very easy but in a practical scenario, it is creating a lot of problems for the developer. So in this tutorial, we will cover local storage-related problems. We have covered the basic use of local storage and session storage inside the Web storage tutorial.

Note – We need to remember that local storage stores all data in string form so we have to be aware of this.

So as we discuss in the web storage chapter.

localStorage.setItem("no", 1); localStorage.getItem("no")); // string

// Solution +localStorage.getItem("no")); // number

But suppose that it is an array value. Here first of we need to stringify the array then, we will store the array when we need to get an array, in that case, we will parse to return a string from local storage.

var arr = ["one", "two", "three"];
localStorage.setItem("array", arr);
localStorage.getItem("array"); // "one,two"; again it is a string value of array

// Solution
localStorage.setItem("array", JSON.stringify(arr));
console.log(JSON.parse(localStorage.getItem("array"))); //["one", "two", "three"]

What about the objects

var obj = { msg: "Hi, I am msg" };
localStorage.setItem("object", obj);
localStorage.getItem("object"); // "[object Object]"

// Solution
localStorage.setItem("object", JSON.stringify(obj));
console.log(JSON.parse(localStorage.getItem("object"))); // { msg: "Hi, I am msg" }

If we want to test the key is exist in web storage –

function isKeyExist(obj, key) {
    return !!obj.getItem(key);

localStorage.setItem("count", 1);

var hasKey = isKeyExist(localStorage, "count");

console.log(hasKey); // true

About the Author: Pankaj Bisht