Furkan's Notes

Furkan's Notes

What is LocalStorage

What is LocalStorage

Listen to this article

1. Definition

The localStorage read-only property of the window interface allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions.

llocalStorage is similar to sessionStorage, except that while localStorage data has no expiration time, sessionStorage data gets cleared when the page session ends — that is, when the page is closed. (localStorage data for a document loaded in a "private browsing" or "incognito" session is cleared when the last "private" tab is closed.)

2. Data Format

The keys and the values stored with localStorage are always in the UTF-16 DOMString format, which uses two bytes per character. As with objects, integer keys are automatically converted to strings.

3. Example

// Setting and item: key: value
localStorage.setItem('myCat', 'Tom');

// Reading an item
const cat = localStorage.getItem('myCat');

// Remove an item
localStorage.removeItem('myCat');

// Clear all items
localStorage.clear();

{% codepen codepen.io/moghaazi/pen/BajWgav %}

4. Advaced Examples

For setting objects or dates we need to convert to strings because localStorage only store string format

let userList = [{name: "David"}, {name: "Kevin"}]
let date = new Date()

// Setting
localStorage.setItem("userList", JSON.stringify(userList))
localStorage.setItem("date", date.toString())

// Reading
userList = JSON.parse(localStorage.getItem("userList"))
date = new Date(localStorage.getItem("date"))

Screenshot of localstorage

 
Share this