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:

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().

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:

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:

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:

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:

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:

 

Leave a Reply

Your email address will not be published. Required fields are marked *