Understanding Local Storage in JavaScript

 

Introduction

Local Storage is a web storage feature in JavaScript that allows developers to store data in the browser persistently. Unlike session storage, local storage data remains available even after the browser is closed and reopened. This is useful for storing user preferences, themes, authentication tokens, and more.


Features of Local Storage

  • Stores key-value pairs.

  • Data persists even after closing the browser.

  • Maximum storage limit is around 5MB.

  • Only accessible within the same origin (same protocol, host, and port).

  • Works asynchronously but does not support automatic expiration.



Using Local Storage in JavaScript

1. Storing Data

To store data in local storage, use the setItem method.

This stores the key username with the value JohnDoe in the local storage.


2. Retrieving Data

To retrieve stored data, use the getItem method.

If the key does not exist, getItem returns null.


3. Removing Data

To remove a specific item from local storage, use the removeItem method.

 

This removes the username key and its value from storage.


4. Clearing All Data

To clear all local storage data, use the clear method.

This removes all stored key-value pairs.


Example: Storing and Displaying User Preferences

Let's create a simple example where a user selects a theme, and we store their preference using local storage.

HTML(index.html)

JavaScript (script.js)


Explanation

  1. When a user clicks on the "Dark Mode" button, setTheme('dark') stores the theme preference in local storage.

  2. The applyTheme() function checks local storage for the saved theme and applies it accordingly.

  3. Even after refreshing or reopening the browser, the chosen theme persists.

Output

  • Clicking "Dark Mode" applies a black background with white text.

  • Clicking "Light Mode" resets to the default white background with black text.

  • Refreshing the page retains the selected theme.

 

Demo Output:


 

Single File Implementation -HTML(index.html)




Conclusion

Local Storage in JavaScript is a powerful tool for persisting data in the browser. It is useful for storing user preferences, authentication details, and lightweight data without requiring a backend. However, since it is accessible via JavaScript, it should not be used to store sensitive information like passwords or private user data.

 



 



 


 



 



Comments

Popular posts from this blog

Building a Full-Stack Task Manager with CRUD Operations (Node.js, Express, MongoDB, REST API, HTML, CSS, JavaScript)

Mastering JavaScript Functions: Declaration, Expression, and Arrow Functions

Mastering Control Structures in JavaScript