Local Storage vs Cookies (The storage showdown)
18 Jun, 2019
Local site storage can open up a ton of possibilities in web design and breath new life into an otherwise static webpage. Whether you just want to do something simple like “show a welcome message only once”, or something a little more complex like “store an array of user preferences”. Without some form of local site storage, this would not be possible.
When it comes to local site storage, there are two main options you have to choose from, Cookies and Local Storage. Each are best suited to a slightly different use case.
A handy tip before we get started. In Chrome, click F12 to open the developer tools and click on “Application”. Here you'll be able to see all the local storage, cookies and session data your site is saving.
//Retrieving stored data
var someData = localStorage.favoriteColor;
//Deleting stored data
Unlike cookies, local storage doesn't have an expiration date. It won't be removed from the user's computer unless the user, either clears their browser storage, or the data is deleted by the site itself.
The main downside of cookies is that they only allow for 4KB of usable space so if you were planning on storing anything larger than that then local storage might be your best bet. Because of this, cookies are usually only used to store small bits of information like session IDs to keep the user logged in.
//Creating a new cookie
document.cookie = "favoriteColor=red";
document.cookie = "favoriteColor=red; expires=Mon, 21 Dec 2020 12:00:00 UTC; path=/";
To delete a cookie simply override the same cookie with an expiry date that has already passed, make sure you specify the same path:
document.cookie = "favoriteColor=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
var someData = document.cookie;
You will then need to parse the string yourself to get the individual cookie values. If you're looking for some premade functions to handle this, or just want to learn more, I would recommend checking out the article w3schools did on cookies here.