Site icon NexGismo

What is Web Storage in JavaScript: Benefits, Precautions, and Examples

What is Web Storage

What is Web Storage

Javascript, when it comes to client-side data storage, has some of the best features that help developers create browser databases. Web storage, which consists of LocalStorage and SessionStorage, is targeted to help retain and manage information between sessions and page refresh. In this article, we are going to learn about what is web storage, its advantages, its usage warnings, as well as its practical applications for a smoother learning curve.

What is Web Storage?

Web storage is an HTML5 feature that enables web applications to keep data within the user’s browser. This data has persistence and can be accessed even if the web browser is opened and closed. There are two types of Web Storage:

LocalStorage

LocalStorage serves to retain data that is intended for retention beyond one browser session. It is useful for data that has to be accessed even after the current user session is terminated and the browser is closed. Some typical use cases of LocalStorage are described below:

Storing Data in LocalStorage:

// Storing data  
localStorage.setItem('username', 'JohnDoe');  
localStorage.setItem('theme', 'dark');  
  
// Retrieving data  
const username = localStorage.getItem('username');  
const theme = localStorage.getItem('theme');  
  
console.log(username); // Output: JohnDoe  
console.log(theme);    // Output: dark  
  
// Removing data  
localStorage.removeItem('username');  
  
// Clearing all data  
localStorage.clear();  

SessionStorage

SessionStorage is used to store information related to a user for a particular page session. All the data therein will be removed when the page session ends which could be, locking of the browser by the user. Here are some common scenarios where SessionStorage is beneficial:

Storing Data in SessionStorage:

// Storing data  
sessionStorage.setItem('sessionID', 'abc123');  
sessionStorage.setItem('cartItems', JSON.stringify(['item1', 'item2', 'item3']));  
  
// Retrieving data  
const sessionID = sessionStorage.getItem('sessionID');  
const cartItems = JSON.parse(sessionStorage.getItem('cartItems'));  
  
console.log(sessionID); // Output: abc123  
console.log(cartItems); // Output: ['item1', 'item2', 'item3']  
  
// Removing data  
sessionStorage.removeItem('sessionID');  
  
// Clearing all data  
sessionStorage.clear();

Benefits of Using Web Storage

Precautions When Using Web Storage

Let’s assume you provide a web application allowing users to switch views from light to dark modes. You can remember the user’s last selected mode using LocalStorage even after they log out.

HTML:

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <meta name="viewport" content="width=device-width, initial-scale=1.0">  
    <title>Theme Switcher</title>  
    <style id="theme-style">  
        /* Default light theme */  
        body {  
            background-color: white;  
            color: black;  
        }  
    </style>  
</head>  
<body>  
    <button id="theme-button">Switch Theme</button>  
  
    <script src="theme-switcher.js"></script>  
</body>  
</html>  

JavaScript (theme-switcher.js):

document.addEventListener('DOMContentLoaded', () => {  
    const themeButton = document.getElementById('theme-button');  
    const themeStyle = document.getElementById('theme-style');  
  
    // Load saved theme from LocalStorage  
    const savedTheme = localStorage.getItem('theme');  
    if (savedTheme) {  
        applyTheme(savedTheme);  
    }  
  
    // Switch theme on button click  
    themeButton.addEventListener('click', () => {  
        const currentTheme = themeStyle.innerHTML.includes('white') ? 'dark' : 'light';  
        applyTheme(currentTheme);  
        localStorage.setItem('theme', currentTheme);  
    });  
  
    function applyTheme(theme) {  
        if (theme === 'dark') {  
            themeStyle.innerHTML = `  
                body {  
                    background-color: black;  
                    color: white;  
                }  
            `;  
        } else {  
            themeStyle.innerHTML = `  
                body {  
                    background-color: white;  
                    color: black;  
                }  
            `;  
        }  
    }  
});  

To elaborate further, a user’s requested theme will be saved in LocalStorage so that it can be used to apply the requested theme every time the page is loaded.

Conclusion

JavaScript Web Storage is one of the features that should be taken full advantage of since it will in one way or the other optimize the application web users experience. Appreciate the merits, observe the rules, and give the hand on the practical instances to be able to exploit LocalStorage and SessionStorage appropriately in your projects. Be it through maintaining user preferences, handling temporary data or keeping data cached Web Storage has got you solved the problem in an elegant and effective manner.

Happy Coding for All Javascript Developers!

Web Storage
  1. MDN Web Docs (Mozilla Developer Network)
Exit mobile version