Web Storage API - localStorage

Ā·

2 min read

Web Storage API - localStorage

localStoragešŸ¤” what's that?

HTML5 introduced localStorage as a way to store data without any expiry date in the web browser.

localStorage is a property that allows apps and websites to store date across browser sessions. Data stored in localStorage has no expiration time, on the contrary data stored in sessionStorage is cleared when the page is closed or when a private tab is closed.

Storage type is object and data is stored in string format as key and value pairs and interger keys are converted to strings automatically. It can be used for storing user preferences, remembering shopping cart data and caching.

How to use localStorage?

localStorage provides following methods to use it.

1. setItem() - to add data

The setItem() method accesses the local storage and adds the data. In this example, myDog is the 'key' which we will use to access the stored info in next step and Boomer is the value.

localStorage.setItem('myDog', 'Boomer');

To store array or object use JOSN.stringify()

const numbers = [1, 2, 3, 4, 5];

localStorage.setItem('numbers', JSON.stringify(numbers);

2. getItem() - to retrieve data

The key is required to retrieve the data stored in localStorage

const dog = localstorage.getItem('myDog');
// dog = 'Boomer'

const numbers = JSON.parse(localStorage.getItem('numbers'));
// numbers = [1, 2, 3, 4, 5]

3. removeItem() - to remove data

It takes the key of the data item as an argument to remove it from the storage.

localstorage.removeItem('myDog');

4. clear() - to clear all data

It's a simple function and takes no arguments to clear all data stored in local storage

localstorage.clear();

5. Length property

It can be used to get the number of name-value pairs stored in localStorage

console.log(localStorage.length);
// 1

Caution

local storage is very useful in some cases, but it's not secure and there is no way to protect your data, and it may not be supported by older browsers. So, do not store any sensitive information using localStorage.

Ā