DEV Community

Cover image for What is LocalStorage
Abdullah Furkan Özbek
Abdullah Furkan Özbek

Posted on • Originally published at blog.furkanozbek.com

What is LocalStorage

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.

localStorage 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();
Enter fullscreen mode Exit fullscreen mode

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"))

Enter fullscreen mode Exit fullscreen mode

Screenshot of localstorage

 Links

Top comments (0)