Storing and retrieving data with localStorage and sessionStorage

Storing and retrieving data with localStorage and sessionStorage

In JavaScript programming, both localStorage and sessionStorage processes are an important part of the API in data and information web storage in JavaScript, it is used to store and process data and information in the client web browser. Both localStorage and sessionStorage processes are storage solutions for data and information in simple key-value order, here the difference between localStorage and sessionStorage is a different concept in terms of how long the data remains constant through these APIs.

Storing and retrieving data with localStorage and sessionStorage

LocalStorage and SessionStorage in JavaScript.

  • localStorage – In JavaScript programming, data and information is stored in localStorage without any expiry time. Here in this process, even if the client web browser is closed and opened again, the data remains persistent in the web browser until it is properly removed by the internet user.
  • sessionStorage – Here in JavaScript, data and information is stored for the time interval of the webpage session. Whereas the stored static data is destroyed automatically when the webpage is closed or the web browser is terminated.

So, let’s understand the LocalStorage and SessionStorage mechanism in JavaScript better.

Use of localStorage in JavaScript.

The localStorage object in JavaScript programming allows the internet user to store data in a permanent order, which means the data will persist in the web browser even after the webpage is reloaded and the browser is restarted.

localStorage element in JavaScript.

  • localStorage.setItem(key, value) – It adds a key-value pair to the localStorage.
  • localStorage.getItem(key) – It retrieves the value associated with the indicated key from the localStorage.
  • localStorage.removeItem(key) – It removes the indicated key-value pair from the localStorage.
  • localStorage.clear() – This clears all key-value pairs in localStorage.

JavaScript storing and retrieving data in localStorage Example.

//here it Storing data in localStorage location

localStorage.setItem(“employeename”, “Vinay”);

localStorage.setItem(“age”, “28”);

localStorage.setItem(“cont”, “9414”);

// here it Retrieving data from localStorage session

const employeename = localStorage.getItem(“employeename”);

const age = localStorage.getItem(“age”);

console.log(employeename); // Result – Vinay

console.log(age); // Result – 28

console.log(cont); // Result – 9414

Example of Removing and Clearing employeedata

// it Remove a specific key-value pair in setitem

localStorage.removeItem(“employename”);

// it used to Clear all items in localStorage session

localStorage.clear();

Use of sessionStorage in JavaScript programming.

In JavaScript programming, the sessionStorage object stores webpage data for a time interval of a webpage session. A webpage session in the current web browser is running as long as the web browser’s browse tab is open. The session data is automatically lost or removed when the web browser tab is closed.

Elements of JavaScript sessionStorage.

  • sessionStorage.setItem(key, value) – It adds a key-value pair to the current webpage session’s sessionStorage.
  • sessionStorage.getItem(key) – It retrieves the value associated with the indicated key from the sessionStorage in the webpage session.
  • sessionStorage.removeItem(key) – It removes the indicated key-value pair from the webpage sessionStorage.
  • sessionStorage.clear() – It clears all the key-value pairs in the sessionStorage.

Storing and retrieving data in JavaScript example.

// here it used to storing data in sessionStorage location

sessionStorage.setItem(“sessionId”, “78123”);

sessionStorage.setItem(“sessionLoggedIn”, “true”);

// here it Retrieving data from the current sessionStorage

const sessionId = sessionStorage.getItem(“sessionId”);

const sessionLoggedIn = sessionStorage.getItem(“sessionLoggedIn”);

console.log(sessionId); // Result – 78123

console.log(sessionLoggedIn); // Result – true

Example: Removing and Clearing Data

// here it used to Remove a specific key-value pair in session

sessionStorage.removeItem(“sessionId”);

// here it used to Clear all items in sessionStorage location

sessionStorage.clear();

Multiple uses of localStorage and sessionStorage in JavaScript programming.

In JavaScript programming, localStorage is usually applied for such webpage data, which is required to be maintained even after the current session in the webpage. For example,

Storing user preferences (session theme settings, language options) etc.

E.g., storing form data in a webpage session. For example, for automatic data storage. Storing purchased items in a shopping cart in an e-commerce website even if the user closes the tab and reopens it later, etc.

In JavaScript programming, sessionStorage is often used to process temporary data. E.g., storing a session ID in a webpage, which expires when the browser tab in a webpage is closed. Tracking an Internet user’s activities in a single webpage session. For example, a step-by-step session-based webpage form.

Storing and retrieving complex data in JavaScript storage.

Both localStorage and sessionStorage can only store strings in a JavaScript session. If the programmer needs to store and process more complex data types, such as objects or arrays, the programmer must sequence and group them in string format by applying the JSON.stringify() function method and then unsequence them when retrieving data using the JSON.parse() function method.

Example of storing object and array in JavaScript storage.

// here we use to Storing an object in localStorage session

const employee = {

empname: “Kunal”,

empage: 19,

email: “kunal@domain.com”

};

// here we Convert the object to a JSON string and store it

localStorage.setItem(“employee”, JSON.stringify(employee));

// here we used to Retrieving the object from localStorage session

const storedemployee = JSON.parse(localStorage.getItem(“employee”));

console.log(storedemployee.empname); // Result – Kunal

console.log(storedemployee.empage); // Result – 19

Limitations of localStorage and sessionStorage in JavaScript.

  • Size limitations – Both localStorage and sessionStorage in JavaScript have a storage limit of approximately 5 MB per domain. This limit is also much less than the internet cookies stored in the web browser, while most modern web browsers are fine for client-side data storage needs.
  • Security – Data stored in localStorage and sessionStorage in JavaScript can be accessed and processed by any web script running in the same domain, so avoid storing confidential data like your secure credentials, passwords or personal information there. If extremely important, use encryption techniques.
  • Synchronous – In a JavaScript web browser session, both localStorage and sessionStorage send and receive webpage data via synchronous APIs, which means that session operations such as setting data, receiving online data, or deleting data can halt the execution of other program code. While this is usually not a problem for small amounts of data, it can create a number of performance issues for large-scale web operations.

Example of localStorage and sessionStorage for a simple counter in JavaScript.

Here you get an example of a simple tester that applies localStorage to maintain a count when a webpage is reloaded.

/// here it Retrieve the tester value from localStorage session, default to 0 value if it is not found

let count = localStorage.getItem(“tester”) ? parseInt(localStorage.getItem(“tester”)) : 0;

// let we Update the tester and display it exist

function updatetester() {

count++;

localStorage.setItem(“tester”, count);

document.getElementById(“tester”).textContent = count;

}

// here it Display the current tester value when the webpage loads in session

document.getElementById(“tester”).textContent = count;

document.getElementById(“increaseButton”).addEventListener(“click”, updatetester);

Explanation of localStorage and sessionStorage for a simple tester.

Here the value of tester is stored in localStorage, due to this it remains stable even after reloading the webpage.

The button here extends the tester, and stores the updated value back to localStorage.

main aspect Between localStorage and sessionStorage session

Session FeaturelocalStorage sessionsessionStorage session
PersistenceHere it Data storage persists, even when the web browser is closedHere web browser Data is cleared, when the web browser or tab is closed
ScopeHere it Available across all tabs and web browser windowsHer it Available only for the current web browser tab
Data Storage LimitIt supports ~5MB per web browser domainHere it supports ~5MB per domain
ExpirationHere is No expiration (must be cleared manually) by user after sessionHere Data expires, when the user page session ends
Use CaseHere it used to Long-term storage (user preferences, etc.)Here its nature is Temporary storage (e.g., session-specific data)

Summary of localStorage and sessionStorage in JavaScript programming.

  • localStorage – Used to keep data in the current web browser session and web browser tab open indefinitely. Ideal for data such as user preferences, e-commerce shopping carts, and the like.
  • sessionStorage – Used for temporary storage during a page session in a web browser. Ideal for session-specific data, such as online form progress or authentication tokens that should be discarded when the browser tab or browser is closed.
  • Data types – Since localStorage and sessionStorage in a JavaScript web browser session store web browser data in string format, complex data type objects, arrays need to be serialized and deserialized by applying the JSON.stringify() and JSON.parse() function methods.

Leave a Reply