ProCodebaseProCodebase
  • ModusA Growth OS for your business, on WhatsAppKiosqSell more. Chase less.AI InterviewerAutomated screening & AI-led interviewsXperto AIAI prep companion for candidatesAI Tools HubResume builder, learning paths & more
  • Pre-Vetted DevelopersScreened, scored and ready to interviewAI-Native DevelopersSenior engineers on an hourly basis
  • Services
  • Features
  • Jobs
  • FAQs
Sign inBook a demo
  • Services
  • Features
  • Jobs
  • FAQs
Sign inBook a demo
ProCodebaseProCodebase

ProCodebase Technologies builds AI products for hiring and growth, and ships software for clients as a technical consultancy. We source, screen and deliver pre-vetted developers — so you only interview high-signal candidates.

Products

  • Modus
  • Kiosq
  • AI Interviewer
  • Xperto AI
  • AI Tools Hub

Hire & build

  • Pre-Vetted Developers
  • AI-Native Developers
  • Technical Consultancy
  • MVP Development
  • Features

Resources

  • Articles
  • Topics
  • Certifications
  • Collections
  • Jobs

Company

  • About Us
  • Contact Us
  • Book a Demo
  • FAQs

© 2026 ProCodebase Technologies. All rights reserved.

  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation

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 Interview Mastery: 20 Essential Concepts

    22/10/2024 · VanillaJS

  • JavaScript Coding Challenges for Interviews

    14/09/2024 · VanillaJS

  • JavaScript Mastery: From Basics to Advanced Techniques

    15/10/2024 · VanillaJS

Related articles

  • Implementing Event Delegation for DOM Events

    14/09/2024 · VanillaJS

  • Memoization in JavaScript

    22/10/2024 · VanillaJS

  • Traverse JSON object to find paths leading to leaf nodes

    12/09/2024 · VanillaJS

  • Mastering JavaScript Fundamentals

    15/10/2024 · VanillaJS

  • Diving into 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