Best guide to understand Local Storage — Javascript
There are many ways to store data in the browser. One of them is localStorage
. localStorage
stores string data in the browser using key. The stored data doesn’t have any expiry time.
Note:- Data stored in either localStorage
is specific to the protocol of the page. Ex- if you store user data in www.example1.com, you can not get this data in www.example2.com. However, you get the data in www.example1.com/xyz.
Lets see the localStorage
APIs-
localStorage.setItem('key','value')
ex- localStorage.setItem('myName','Aquib')
setItem
is used for storing the item in localStorage. It accepts “key” and “value” in string form.
Here key is myName and the value is Aquib. You can store any data type in localStorage by converting it to string usingJSON.stringify(Any)
. Here “Any” can be an object, array etc.
ex- const person = {name:'Aquib',
isHappy:true,
age:25,
hobbies:['coding', 'playing', 'eating']} const personString = JSON.stringify(person) localStorage.setItem('person', personString)
Now the data is stored in the localStorage. You can see it in the developers tool.
localStorage.getItem('key')
ex- const myName = localStorage.getItem('myName')
console.log(myName)
output- Aquib
const person = localStorage.getItem('person') //person is string
const personJson = JSON.parse(person) //converting person into json
console.log(personJson)
output- {"name":"Aquib","isHappy":true,"age":25,
"hobbies": ["coding","playing","eating"]
}
getItem
is used for fetching the item from localStorage.
Use the same key “myName, person” for fetching data.getItem
gives you stored data in string form. To convert stored data into original form, useJSON.parse()
localStorage.removeItem('key')
ex- localStorage.removeItem('myName')
localStorage.removeItem('person')
const myName = localStorage.getItem('myName') //output- null
const person = localStorage.getItem('person') //output- null
removeItem
is used to remove the stored data from localStorage.
Use same key “myName” and “ person” for removing data. As data is removed, the value of “myName” and “ person” is null.