The Wayback Machine - https://web.archive.org/web/20241226203924/https://www.geeksforgeeks.org/javascript-localstorage/
Open In App

JavaScript localStorage

Last Updated : 04 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

JavaScript localStorage is a web storage feature that allows you to store key-value pairs in a browser. Data persists even after the browser is closed, providing a method to save and retrieve data across sessions, enhancing user experience by maintaining state and preferences.

 Syntax

ourStorage = window.localStorage;

The above will return a storage object which can be used to access the current origin’s local storage space.

Properties and Methods of localStorage

MethodDescription
setItem(key, value)Stores key/value pair
getItem(key)Returns the value in front of the key
key(index)Gets the key at a given index
lengthReturns the number of stored items (data)
removeItem(key)Removes the given key with its value
clear()Deletes everything from the storage

Key Features of localStorage

  • Origin-Bound Storage: Data is stored per domain and is not shared across different origins.
  • Persistent Storage: Data remains intact even if the browser is closed or the operating system is rebooted. It will be available until manually cleared.
  • Storage Limit: The storage limit for localStorage is 5MB, which is greater than the 4MB limit for cookies.
  • No Automatic Transmission: Unlike cookies, localStorage data is not sent with every HTTP request, making it a more efficient option for client-side storage.

Example: Using localStorage

This example demonstrates using localStorage to store, update, retrieve, and delete key/value pairs in the browser. It shows setting items, updating them, retrieving data by key, checking stored items count, and clearing the storage.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" 
          content="IE=edge">
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1.0">
    <title>JavaScript localStorage</title>

    <style>
        div {
            width: 300px;
            height: 200px;
            padding: 20px;
            border: 2px solid black;
            background-color: green;
            color: white;
            margin: auto;
            text-align: center;
            font-size: 1.5rem;
        }

        .box {
            box-sizing: border-box;
        }
    </style>
</head>

<body>

    <div class="box">GeeksforGeeks</div>

    <script>

        // Saving data as key/value pair
        localStorage.setItem("name", "GeeksforGeeks");
        localStorage.setItem("color", "green");

        // Updating data
        localStorage.setItem("name", "GeeksforGeeks(GfG)");
        localStorage.setItem("color", "Blue");

        // Get the data by key
        let name = localStorage.getItem("name");
        console.log("This is - ", name);
        let color = localStorage.getItem("color");
        console.log("Value of color is - ", color);

        // Get key on a given position
        let key1 = localStorage.key(1);
        console.log(key1);

        // Get number of stored items
        let items = localStorage.length;
        console.log("Total number of items is ", items);

        // Remove key with its value
        localStorage.removeItem("color");

        // Delete everything
        localStorage.clear();
    </script>
</body>

</html>

Output: 

Image

Viewing localStorage Data

To view the data stored in the browser’s localStorage:

  • Open your web page in the browser.
  • Right-click and select “Inspect” or press Ctrl+Shift+I (Windows) or Cmd+Option+I (Mac).
  • Go to the “Application” tab.
  • In the left-hand menu, under “Storage,” select “Local Storage.”
  • Saving data as key/value pair

Image

Updating data 

Image

Get data, index of a key, and number of stored items

Image

Remove a key with its value

Image

Delete everything in storage

Image

Conclusion

localStorage is an effective tool for storing data persistently within the browser. It provides methods to easily set, retrieve, and manage data, ensuring it remains available across sessions until explicitly cleared. By understanding and utilizing localStorage, developers can enhance the user experience by maintaining state and preferences across browsing sessions.

JavaScript localStorage- FAQs

1. Can localStorage store objects?

Yes, but you need to serialize the object to a string using JSON.stringify() before storing, and deserialize it using JSON.parse() when retrieving.

2. How is localStorage different from sessionStorage?

localStorage retains data even after the browser is closed and reopened, whereas sessionStorage only keeps data for the duration of the page session (until the browser tab or window is closed).

3. Can localStorage be shared across different domains?

No, localStorage is domain-specific. Data stored in localStorage is only accessible from the same domain that stored it, ensuring data privacy and security between different websites.

4. Is localStorage secure for sensitive data?

No, localStorage is not secure for storing sensitive data such as passwords or personal information. Data stored in localStorage can be accessed by any script running on the same domain, including potential malicious scripts.

5. How can I clear all data from localStorage?

To clear all data from localStorage, use the clear() method

localStorage.clear();



Next Article

Similar Reads

three90RightbarBannerImg