Skip to content

Instantly share code, notes, and snippets.

@dikshagoyal26
Created September 14, 2020 03:52
Show Gist options
  • Save dikshagoyal26/64eb52ea4a3fcc7bed4351c80397aa84 to your computer and use it in GitHub Desktop.
Save dikshagoyal26/64eb52ea4a3fcc7bed4351c80397aa84 to your computer and use it in GitHub Desktop.
Storage Methods

There are three different types of storage in Javascript.

  1. Local Storage
  2. Session Storage
  3. Cookies

Local Storage

Data stored in local storage has no expiration time, its available until the user clears the browser cache. Data in local Storage is also not affected in case of page reloads or closing and reopening of tabs/browser. While data stored while browsing in a private tab is cleared when the tab is closed. local storage can only be read by the client-side Accessed with window.localStorage

To save an Item into the local Storage localStorage.setItem('name','John Doe') or localStorage.name = 'John Doe'

To get Item from local Storage let name = localStorage.getItem('name') or let name = localStorage.name

To remove an Item from localStorage localStorage.removeItem('name')

To clear localStorage localStorage.clear()

Session Storage

Data stored in session storage is available only for current session of the user. Data is removed in case of page reloads or closing and reopening of tabs/browser. Opening a page in a new tab or window creates a new session . While data stored while browsing in a private tab is cleared when the tab is closed. Session storage can only be read by the client-side. Accessed with window.sessionStorage

To save an Item into the session Storage sessionStorage.setItem('name','John Doe') or sessionStorage.name = 'John Doe'

To get Item from session Storage let name = sessionStorage.getItem('name') or let name = localStorage.name

To remove an Item from session Storage sessionStorage.removeItem('name')

To clear session Storage sessionStorage.clear()

Cookies

Cookies are small files which are located on a user’s computer. A cookie can simply be used if there is a large amount of information to store. Cookies are mainly for reading server-side. Cookies send server information back with every HTTP request.

Cookies are saved in name-value pairs like: name = John Doe

Read all cookies accessible from current location allCookies = document.cookie;

Write a new cookie document.cookie = 'name=John Doe';

Expiry date can be added in a cookie (in UTC time). By default, the cookie is deleted when the browser is closed document.cookie = "name=John Doe; expires=Thu, 16 Sept 2020 12:00:00 UTC";

With a path parameter, browser gets to know the path the cookie belongs to. document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

To delete a cookie document.cookie = "username=; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment