logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Mastering Local Storage and Session Storage in Vanilla JavaScript

author
Generated by
Abhishek Goyan

15/10/2024

javascript

Sign in to read full article

Introduction to Web Storage

Web Storage is a powerful feature in modern browsers that allows web applications to store data locally within the user's browser. This capability enhances performance, reduces server load, and enables offline functionality. In this blog post, we'll explore two key components of Web Storage: Local Storage and Session Storage.

Local Storage: Persistent Data Storage

Local Storage provides a way to store data in the browser that persists even after the browser window is closed. This makes it ideal for saving user preferences, caching data, or maintaining application state across sessions.

Using Local Storage

Here's how you can use Local Storage in vanilla JavaScript:

// Storing data localStorage.setItem('username', 'JohnDoe'); // Retrieving data const username = localStorage.getItem('username'); console.log(username); // Output: JohnDoe // Removing a specific item localStorage.removeItem('username'); // Clearing all data in Local Storage localStorage.clear();

Storing Complex Data

Local Storage only supports string values. To store objects or arrays, you'll need to convert them to JSON:

const user = { name: 'John Doe', age: 30, preferences: ['reading', 'coding'] }; // Storing an object localStorage.setItem('user', JSON.stringify(user)); // Retrieving and parsing the object const storedUser = JSON.parse(localStorage.getItem('user')); console.log(storedUser.name); // Output: John Doe

Session Storage: Temporary Data Storage

Session Storage is similar to Local Storage but with a key difference: data stored in Session Storage is cleared when the browser tab is closed. This makes it useful for storing temporary data that's only needed for the duration of a browsing session.

Using Session Storage

The API for Session Storage is identical to Local Storage:

// Storing data sessionStorage.setItem('currentPage', 'home'); // Retrieving data const currentPage = sessionStorage.getItem('currentPage'); console.log(currentPage); // Output: home // Removing a specific item sessionStorage.removeItem('currentPage'); // Clearing all data in Session Storage sessionStorage.clear();

Choosing Between Local Storage and Session Storage

When deciding which storage method to use, consider the following:

  • Use Local Storage for data that should persist across browser sessions (e.g., user preferences, authentication tokens).
  • Use Session Storage for temporary data that's only needed for the current browsing session (e.g., form data, shopping cart items).

Storage Event

When working with Local Storage in multiple windows or tabs, you can listen for changes using the storage event:

window.addEventListener('storage', (event) => { console.log('Key changed:', event.key); console.log('Old value:', event.oldValue); console.log('New value:', event.newValue); console.log('Storage area:', event.storageArea); });

This event fires when Local Storage is modified in other windows or tabs, allowing you to sync data across multiple instances of your application.

Storage Limits and Security Considerations

While Web Storage is incredibly useful, it's important to be aware of its limitations:

  1. Storage capacity varies by browser but is typically around 5-10MB.
  2. Data stored is not encrypted by default, so avoid storing sensitive information.
  3. Web Storage is vulnerable to XSS attacks, so always sanitize data before storing and retrieving.

Practical Examples

Remembering User Preferences

function saveThemePreference(theme) { localStorage.setItem('theme', theme); } function loadThemePreference() { return localStorage.getItem('theme') || 'light'; } // Usage saveThemePreference('dark'); const currentTheme = loadThemePreference(); applyTheme(currentTheme);

Implementing a Shopping Cart

function addToCart(product) { let cart = JSON.parse(sessionStorage.getItem('cart')) || []; cart.push(product); sessionStorage.setItem('cart', JSON.stringify(cart)); } function getCart() { return JSON.parse(sessionStorage.getItem('cart')) || []; } // Usage addToCart({ id: 1, name: 'Widget', price: 9.99 }); const cartItems = getCart(); displayCart(cartItems);

Conclusion

Local Storage and Session Storage are powerful tools in the JavaScript developer's toolkit. By understanding their capabilities and differences, you can enhance your web applications with efficient client-side data storage, leading to improved performance and user experience.

Popular Tags

javascriptweb storagelocal storage

Share now!

Like & Bookmark!

Related Collections

  • JavaScript Coding Challenges for Interviews

    14/09/2024 | VanillaJS

  • JavaScript Interview Mastery: 20 Essential Concepts

    22/10/2024 | VanillaJS

  • JavaScript Mastery: From Basics to Advanced Techniques

    15/10/2024 | VanillaJS

Related Articles

  • Mastering Test-Driven Development in Vanilla JavaScript

    15/10/2024 | VanillaJS

  • Unleashing the Power of Progressive Web Apps with Vanilla JavaScript

    15/10/2024 | VanillaJS

  • Diving into Vanilla JavaScript

    15/10/2024 | VanillaJS

  • Understanding Rest and Spread Operators in Vanilla JavaScript

    22/10/2024 | VanillaJS

  • Mastering Error Handling and Debugging in Vanilla JavaScript

    15/10/2024 | VanillaJS

  • Mastering Asynchronous JavaScript

    15/10/2024 | VanillaJS

  • Mastering Control Structures in JavaScript

    15/10/2024 | VanillaJS

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design