LocalStorage in JavaScript

LocalStorage is a type of web storage that allows JavaScript websites and apps to store and access data right in the browser with no expiration date. This means the data stored in the browser will persist even after the browser window has been closed.

To achieve this JavaScript provide read-only localStorage property.

 Methods for LocalStorage:

  1. setItem(): Add key and value to localStorage
  2. getItem(): Retrieve a value by the key from localStorage
  3. removeItem(): Remove an item by key from localStorage
  4. clear(): Clear all localStorage
  5. key(): Passed a number to retrieve nth key of a localStorage

Detailed explanation of the above methods is below:

setItem()

This method is used to store values in the localStorage object.

It takes two parameters, a key and a value. Example:

1.	window.localStorage.setItem('name', 'James Smith');

where name is the key and “James Smith” is the value. To store arrays or objects you have to convert them to strings.

Example: Use JSON.stringify() method before passing to setItem().

1.	const user = {  
2.	    name: " James Smith",  
3.	    address: "xyz",  
4.	}  
5.	  
6.	window.localStorage.setItem('user', JSON.stringify(user));  

getItem()

The getItem() method used to access data stored in the browser’s localStorage object.

It accepts one parameter i.e key and returns the value as a string.

Example: Following code retrieve the user key stored above:

1.	window.localStorage.getItem('user');

This returns a string with value as:

“{“name”: ”James Smith”, ”address”: ”xyz”}”

To use this value, you would have to convert it back to an object.

Example:

1.	JSON.parse(window.localStorage.getItem('user'));

removeItem()

The removeItem() method is used to remove an item from localStorage object. It takes key as parameter which you want to delete (if exists otherwise nothing happens).

Example:

1.	window.localStorage.removeItem('user’);

It will remove item from localStorage with key ‘user’.

clear()

This method clears the entire storage of all records for that domain. It does not receive any parameters. Example:

1.	window.localStorage.clear();

key()

The key() method is used to iterate through keys. It takes index number as parameter and allows you to pass a number or index to local storage to retrieve the name of the key.

Example:

1.	var KeyName = window.localStorage.key(index);

 

Leave a Reply