These are storage methods provided by the browser, to store information on the user's browser.
Now let's see what's the difference between them and how can we use them.
Local storage
➡️ Capacity - 10MB
➡️ Expiry - Never
➡️ Data accessibility - Any tab of a browser
➡️ Syntax -
1️⃣ Storing data
localStorage.setItem('name', 'Ashwani')
// Here the first parameter is the name and the second parameter is the value, both need to be in string format
2️⃣ Getting Data
localStorage.getItem('name')
// We need to specify the key for which we want to get the data
3️⃣ Removing Data
localStorage.removeItem('name')
Session Storage
➡️ Capacity - 5MB
➡️ Expiry - On tab close
➡️ Data accessibility - Same tab
➡️ Syntax - Exact same methods as localStorage
1️⃣ Storing data
sessionStorage.setItem('name', 'Ashwani')
2️⃣ Getting Data
sessionStorage.getItem('name')
3️⃣ Removing Data
sessionStorage.removeItem('name')
Cookies
➡️ Capacity - 4KB
➡️ Expiry - Manually set
➡️ Data accessibility - Any tab of a browser
➡️ Syntax -
document.cookie is used both for setting and getting the data.
1️⃣ Storing data
document.cookie = 'name = Ashwani'
⬇️ Manually setting expiry - we can use the expiry or max-age property.
document.cookie = "lastName = jha ; max-age = 10"
2️⃣ Getting Data
console.log(document.cookie)
// There's not any way to get a particular cookie data.
⭐ As we now know that all these three are methods to store data in the browser, but with cookie we can store data on the server as well.
Now, let's conclude this -
Most of the time we prefer local storage or session storage due to its simple syntax and large capacity, we use cookie when we need data on the server (e.g. authentication).
Top comments (0)