HTML DOM Storage length property

The HTML DOM Storage length property returns the number of key-value pairs stored in the browser's storage object. This property works with both localStorage and sessionStorage objects, providing a simple way to count stored items.

Syntax

Following is the syntax for the Storage length property −

localStorage.length
sessionStorage.length

Return Value

The length property returns an integer representing the number of items currently stored in the storage object. If no items are stored, it returns 0.

Example − localStorage Length

Following example demonstrates how to get the number of items in localStorage −

<!DOCTYPE html>
<html>
<head>
   <title>localStorage Length Property</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>localStorage Length Example</h2>
   <p>Click the button to see how many items are stored in localStorage:</p>
   
   <button onclick="addItem()">Add Item</button>
   <button onclick="getLength()">Get Length</button>
   <button onclick="clearStorage()">Clear Storage</button>
   
   <p id="result" style="margin-top: 20px; font-weight: bold;"></p>
   
   <script>
      let itemCounter = 1;
      
      function addItem() {
         localStorage.setItem("item" + itemCounter, "Value " + itemCounter);
         itemCounter++;
         document.getElementById("result").innerHTML = "Item added! Current length: " + localStorage.length;
      }
      
      function getLength() {
         var length = localStorage.length;
         document.getElementById("result").innerHTML = "Number of items in localStorage: " + length;
      }
      
      function clearStorage() {
         localStorage.clear();
         itemCounter = 1;
         document.getElementById("result").innerHTML = "Storage cleared! Length is now: " + localStorage.length;
      }
   </script>
</body>
</html>

This example allows you to add items, check the length, and clear the storage to see how the length property changes −

localStorage Length Example
Click the button to see how many items are stored in localStorage:
[Add Item] [Get Length] [Clear Storage]
(Initially shows: Number of items in localStorage: 0)

Example − sessionStorage Length

Following example shows the length property with sessionStorage −

<!DOCTYPE html>
<html>
<head>
   <title>sessionStorage Length Property</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>sessionStorage Length Example</h2>
   <p>Session storage data persists only for the current browser session.</p>
   
   <input type="text" id="keyInput" placeholder="Enter key name">
   <input type="text" id="valueInput" placeholder="Enter value">
   <button onclick="addSessionItem()">Add to Session</button>
   <button onclick="checkSessionLength()">Check Length</button>
   
   <div id="output" style="margin-top: 20px; padding: 10px; border: 1px solid #ccc;"></div>
   
   <script>
      function addSessionItem() {
         var key = document.getElementById("keyInput").value;
         var value = document.getElementById("valueInput").value;
         
         if (key && value) {
            sessionStorage.setItem(key, value);
            document.getElementById("output").innerHTML = 
               "Added '" + key + "' to sessionStorage. Current length: " + sessionStorage.length;
            
            // Clear inputs
            document.getElementById("keyInput").value = "";
            document.getElementById("valueInput").value = "";
         } else {
            document.getElementById("output").innerHTML = "Please enter both key and value.";
         }
      }
      
      function checkSessionLength() {
         var length = sessionStorage.length;
         var items = [];
         
         for (var i = 0; i < length; i++) {
            var key = sessionStorage.key(i);
            items.push(key + ": " + sessionStorage.getItem(key));
         }
         
         document.getElementById("output").innerHTML = 
            "<strong>sessionStorage Length: " + length + "</strong><br>" +
            "Items: " + (items.length > 0 ? items.join(", ") : "None");
      }
   </script>
</body>
</html>

This example demonstrates adding items to sessionStorage and checking the length dynamically −

sessionStorage Length Example
Session storage data persists only for the current browser session.
[Enter key name] [Enter value] [Add to Session] [Check Length]
(Shows current sessionStorage length and stored items)

Practical Use Cases

The Storage length property is commonly used in the following scenarios −

  • Storage validation − Check if storage is empty before retrieving data

  • Storage limits − Monitor storage usage and prevent exceeding browser limits

  • Data management − Clean up storage when it contains too many items

  • User interface updates − Display storage status or item counts to users

Example − Storage Management

Following example shows a practical storage management system using the length property −

<!DOCTYPE html>
<html>
<head>
   <title>Storage Management System</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Storage Management System</h2>
   
   <div style="margin-bottom: 20px;">
      <button onclick="addRandomData()">Add Random Data</button>
      <button onclick="checkStorageStatus()">Check Status</button>
      <button onclick="cleanupStorage()">Cleanup Storage</button>
   </div>
   
   <div id="status" style="padding: 10px; border: 1px solid #ddd; background-color: #f9f9f9;">
      Click "Check Status" to see storage information.
   </div>
   
   <script>
      function addRandomData() {
         var timestamp = Date.now();
         var randomValue = "data_" + Math.random().toString(36).substr(2, 9);
         localStorage.setItem("item_" + timestamp, randomValue);
         checkStorageStatus();
      }
      
      function checkStorageStatus() {
         var localLength = localStorage.length;
         var sessionLength = sessionStorage.length;
         var totalSize = JSON.stringify(localStorage).length;
         
         document.getElementById("status").innerHTML = 
            "<strong>Storage Status:</strong><br>" +
            "localStorage items: " + localLength + "<br>" +
            "sessionStorage items: " + sessionLength + "<br>" +
            "Approximate localStorage size: " + totalSize + " characters<br>" +
            "Status: " + (localLength > 10 ? "<span style='color: orange;'>Consider cleanup</span>" : "<span style='color: green;'>OK</span>");
      }
      
      function cleanupStorage() {
         if (localStorage.length > 5) {
            var keysToRemove = [];
            for (var i = 0; i < localStorage.length; i++) {
               var key = localStorage.key(i);
               if (key && key.startsWith("item_")) {
                  keysToRemove.push(key);
               }
            }
            
            // Remove old items
            keysToRemove.forEach(function(key) {
               localStorage.removeItem(key);
            });
            
            checkStorageStatus();
         } else {
            document.getElementById("status").innerHTML = "No cleanup needed. Storage length: " + localStorage.length;
         }
      }
      
      // Initial status check
      checkStorageStatus();
   </script>
</body>
</html>

This management system uses the length property to monitor storage usage and perform cleanup when needed −

Storage Management System
[Add Random Data] [Check Status] [Cleanup Storage]

Storage Status:
localStorage items: 0
sessionStorage items: 0  
Approximate localStorage size: 2 characters
Status: OK
Storage Length Property Workflow Check Storage Length Evaluate Count Take Action (Add/Remove) localStorage.length if (length > limit) clear() or setItem() Returns: Number of key-value pairs (0 if empty) Works with both localStorage and sessionStorage

Browser Compatibility

The Storage length property is supported in all modern browsers that support Web Storage API, including Chrome, Firefox, Safari, Edge, and Internet Explorer 8+. Both localStorage and sessionStorage objects support the length property consistently across browsers.

Conclusion

The HTML DOM Storage length property provides a simple way to count stored items in localStorage or sessionStorage. It returns an integer representing the number of key-value pairs, making it useful for storage management, validation, and user interface updates. This property is essential for building efficient web applications that manage browser storage effectively.

Updated on: 2026-03-16T21:38:54+05:30

220 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements