Sling Academy
Home/JavaScript/Use localStorage and sessionStorage in JavaScript

Use localStorage and sessionStorage in JavaScript

Last updated: December 13, 2024

Web storage is an essential aspect of modern web applications that allows you to store data directly within a user's browser. JavaScript provides two types of web storage: localStorage and sessionStorage. Both these storages enable you to save data locally which can then be accessed and manipulated using JavaScript. This is particularly useful for saving user preferences, caching data, or maintaining state between browser sessions without relying on server-side technologies.

Understanding localStorage

localStorage is a type of web storage that can store data with no expiration date. This means the data will be available even after the browser is closed and reopened. The data persists until it is deleted explicitly or the user clears the browser’s storage.

Data in localStorage is stored in the form of key-value pairs stored as strings. Here is a basic example of how you can set, retrieve, and remove data using localStorage.

// Storing data in localStorage
localStorage.setItem('username', 'JohnDoe');

// Retrieving data from localStorage
const username = localStorage.getItem('username'); // Returns 'JohnDoe'

// Removing data from localStorage
localStorage.removeItem('username');

// Clearing all data from localStorage
localStorage.clear();

Understanding sessionStorage

sessionStorage works in a similar way to localStorage, but with one key difference: the data stored in sessionStorage is available only during the session of the browser. Once the browser is closed, all the data in sessionStorage is cleared. This is useful when you need to temporarily store data that should not persist beyond the current browsing session.

Just like localStorage, sessionStorage stores data in key-value pairs, both being strings. Here is how you can use sessionStorage:

// Storing data in sessionStorage
sessionStorage.setItem('sessionUsername', 'JaneDoe');

// Retrieving data from sessionStorage
const sessionUsername = sessionStorage.getItem('sessionUsername'); // Returns 'JaneDoe'

// Removing data from sessionStorage
sessionStorage.removeItem('sessionUsername');

// Clearing all data from sessionStorage
sessionStorage.clear();

Key Differences between localStorage and sessionStorage

While both localStorage and sessionStorage enable storage of data on the client-side, there are several important differences:

  • Lifetime: Data in localStorage persists until it is deleted manually. On the other hand, sessionStorage data is erased when the browsing session ends.
  • Scope: Both localStorage and sessionStorage are specific to the protocol of the page. For example, different storage is maintained for HTTP and HTTPS protocols.
  • Capacity: Although both can store around 5-10 MB of data depending on the browser, localStorage theoretically can handle more data, and data limitations are governed by different browsers.

Browser Compatibility

Both localStorage and sessionStorage are well-supported across all major browsers, including Chrome, Firefox, Safari, and Edge. However, as with any web technology, it's always good practice to ensure compatibility before implementing.

if (typeof(Storage) !== "undefined") {
  // Code for localStorage/sessionStorage.
  console.log("Web Storage is supported!");
} else {
  // Sorry! No Web Storage support..
  console.log("Web Storage is not supported!");
}

Conclusion

Understanding and properly using localStorage and sessionStorage is crucial as these tools provide powerful ways to enhance user experience by making web applications more responsive and feature-rich. Their ease of use and wide support across browsers make them useful additions to the web developer's toolkit.

Next Article: Persist User Preferences and Sessions via JavaScript Storage

Previous Article: Store Data Client-Side Using JavaScript Storage APIs

Series: Web APIs – JavaScript Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration