This content originally appeared on DEV Community and was authored by Joe Steinbring
Back in 2012, I posted How to store JavaScript values persistently, locally (a post that is apparently a bit broken). I figured that it might be time to revisit the topic.
Let’s start by looking at how to create and read cookies, first.
In the above example, we are creating a cookie called “cookieName” and setting it to expire in 365 days. Cookies have the downside that you can only store 4kb of data per domain and you have to set the expiry manually.
So, let’s look at localStorage, next.
In the above localStorage example, we are creating a localStorage object that’s called “lsName”. It has the benefit of never expiring and having a capacity of 5mb per domain.
So, what about sessionStorage?
In the above sessionStorage example, we are creating an object called “ssName”. Like localStorage, sessionStorage has a capacity of 5mb per domain. Unlike localStorage, the object is only available on the tab where the object was created. As soon as the tab is closed, the object expires.
Local storage and session storage are also referred to as web storage. Really, the only reason to use cookies instead of web storage is if you are writing for an HTML4-based browser, which would be crazy.
This content originally appeared on DEV Community and was authored by Joe Steinbring
Joe Steinbring | Sciencx (2021-08-02T19:15:14+00:00) Cookies vs localStorage vs sessionStorage in JavaScript. Retrieved from https://www.scien.cx/2021/08/02/cookies-vs-localstorage-vs-sessionstorage-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.