Skip to content
the poor coder

javascript set local storage value

Poor Man
Published
Reading time
1 min read
On this page

JavaScript Set Local Storage Value#

Local storage is a mechanism to store key-value pairs in the browser which can be accessed later. These values persist even after the browser is closed and can be accessed again on the next session on the same browser.

Using setItem()#

The setItem() method is used to set a value in local storage.

Text

localStorage.setItem("key", "value");

The first argument is the key and the second argument is the value. Both arguments are strings. The key is used to retrieve the value later. The value can be any data type which can be converted to a string.

Using dot notation#

Values in local storage can also be set using dot notation:

Text

localStorage.key = "value";

This method is equivalent to using setItem().

Checking for errors#

If you run into an error while trying to save data to local storage, it's important to check if the storage is full. If the storage is full, the user may need to clear some space before trying again. You can use the try...catch statement:

Text

try {
  localStorage.setItem("key", "value");
} catch (error) {
  if (error.code === DOMException.QUOTA_EXCEEDED_ERR) {
    alert("Local Storage is Full!");
  }
}

In the above example, if there is an error while setting an item in local storage, we check if the error code is DOMException.QUOTA_EXCEEDED_ERR, which means the storage is full.

Now you know how to set values in local storage. You can use this feature to store user preferences or remember user settings across sessions.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC