Skip to content
the poor coder

check local storage javascript

Poor Man
Published
Reading time
1 min read
On this page

Check local storage in Javascript#

Local storage in Javascript is a way to store data in the user's browser, which can be accessed even after the user closes the browser and comes back later. It's a useful tool for web developers who want to store data that can be used across multiple sessions.

Checking local storage#

To check local storage in Javascript, you can use the following code:

Text

if (typeof(Storage) !== "undefined") {
  // Code for localStorage/sessionStorage.
  // Store data
  localStorage.setItem("name", "Raju");
  // Retrieve data
  var storedName = localStorage.getItem("name");
} else {
  // Sorry! No Web Storage support..
}

In the code above, we first check if the browser supports local storage using the typeof operator. If it does, we can use localStorage.setItem() to store data and localStorage.getItem() to retrieve data.

If the browser doesn't support local storage, we can display an error message or use an alternative method for storing data.

Multiple ways to check local storage#

There are multiple ways to check local storage in Javascript. Here are a few examples:

  • Using try-catch blocks:
Text

try {
  var storedName = localStorage.getItem("name");
} catch (e) {
  // Handle exceptions
}
  • Using ternary operators:
Text

var storedName = (typeof(Storage) !== "undefined") ? localStorage.getItem("name") : null;

These methods all achieve the same result, but the specific implementation may vary depending on the developer's preferences or requirements.

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