john c. j. john c. j. - 1 month ago 6
Javascript Question

Get the last stored localStorage item

Say we have:

localStorage.setItem("key1", "value1");
localStorage.setItem("key2", "value2");
localStorage.setItem("key3", "value3");
localStorage.setItem("key4", "value4");
localStorage.setItem("key5", "value5"); // the last one


Is there a way to get the last stored item, without a knowledge of its key? So, we don't know if its key is
key5
or
key10
or
fbjfbjfkbjkf
. We just want to get this item.

Something like?

localStorage.getLastStoredItem();

Answer

localStorage has no exact concept (it is implementation-defined) of the order of items stored, it should be used as a key-value store.

The simplest solution for you would be to somehow store the last key entered. For example, you can create a wrapper function that stores your items, and updates the last key:

var lastKey; // somewhere in your code, in the outer scope of `add()` and `getLast()`

// ...

function add(key, value) {
    lastKey = key;                    
    localStorage.setItem(key, value);
}

function getLast() {
    return localStorage.getItem(lastKey);
}

Here's a sample Fiddle

Maybe you can make an object for your storage purposes that will keep track of all of this. You can also encapsulate the lastKey as a private variable through a closure so you can't accidentally change it:

var MyStorage = {};
(function(s) {
    var lastKey;
    s.add = function(key, value) { /* ... */ };
    s.getLast = function() { /* ... */ }
})(MyStorage);

Now only MyStorage.add() and MyStorage.getLast() can access the lastKey. Also, if you use a wrapper object like MyStorage, you can for example change your store to sessionStorage internally without affecting any code using MyStorage


EDIT

As suggested in the comments by user2181397 and nnnnnn, if you want to persist the value of lastKey through application restarting, you can also store it in localStorage (or sessionStorage depending on your app logic):

var lastKey = localStorage.getItem('lastKey');

Or in the object:

var MyStorage = {};
(function(s) {
    var lastKey = localStorage.getItem('lastKey');
    s.add = function(key, value) { /* ... */ };
    s.getLast = function() { /* ... */ }
})(MyStorage);

EDIT2:

Something like? localStorage.getLastStoredItem;

Another way could be to add the above method directly to localStorage by overriding the Storage.prototype methods instead of creating the MyStorage object:

(function(s) {
    var lastKey = localStorage.getItem('lastKey');

    var _setItem = Storage.prototype.setItem;          // remember the original setItem
    Storage.prototype.setItem = function(key, value) { // define the new setItem
        if (this === window.localStorage) {            // make sure we are calling localStorage's methods
            lastKey = key;                             // remember the last key
        } 
        _setItem.apply(this, arguments);               // call the original setItem
    }

    Storage.prototype.getLast = function() {           // create the necessary custom method to get the last item stored
        if (this === window.localStorage) {            // make sure we are calling localStorage's methods
            return this.getItem.call(this, lastKey);
        }
    }
})();

Usage:

localStorage.setItem('key1', 'val1');
console.log(localStorage.getLast()); // logs 'val1'

Here's a sample Fiddle

NOTE: Since we are editing Storage.prototype, extending this functionality to other Storage API methods is just a matter of removing the if (this === localStorage) or adding another condition to it.

Comments