javascript set local storage value

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.


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:


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:


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.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe