Is Localstorage.Getitem('Item') Better Than Localstorage.Item or Localstorage['Item']

Is localStorage.getItem('item') better than localStorage.item or localStorage['item']?

Both direct property access (localStorage.foo or localStorage['foo']) and using the functional interface (localStorage.getItem('foo')) work fine. Both are standard and cross-browser compatible.* According to the spec:

The supported property names on a Storage object are the keys of each key/value pair currently present in the list associated with the object, in the order that the keys were last added to the storage area.

They just behave differently when no key/value pair is found with the requested name. For example, if key 'foo' does not exist, var a = localStorage.foo; will result in a being undefined, while var a = localStorage.getItem('foo'); will result in a having the value null. As you have discovered, undefined and null are not interchangeable in JavaScript. :)

EDIT: As Christoph points out in his answer, the functional interface is the only way to reliably store and retrieve values under keys equal to the predefined properties of localStorage. (There are six of these: length, key, setItem, getItem, removeItem, and clear.) So, for instance, the following will always work:

localStorage.setItem('length', 2);
console.log(localStorage.getItem('length'));

Note in particular that the first statement will not affect the property localStorage.length (except perhaps incrementing it if there was no key 'length' already in localStorage). In this respect, the spec seems to be internally inconsistent.

However, the following will probably not do what you want:

localStorage.length = 2;
console.log(localStorage.length);

Interestingly, the first is a no-op in Chrome, but is synonymous with the functional call in Firefox. The second will always log the number of keys present in localStorage.

* This is true for browsers that support web storage in the first place. (This includes pretty much all modern desktop and mobile browsers.) For environments that simulate local storage using cookies or other techniques, the behavior depends on the shim that is used. Several polyfills for localStorage can be found here.

How to store objects in HTML5 localStorage/sessionStorage

Looking at the Apple, Mozilla and Mozilla again documentation, the functionality seems to be limited to handle only string key/value pairs.

A workaround can be to stringify your object before storing it, and later parse it when you retrieve it:

var testObject = { 'one': 1, 'two': 2, 'three': 3 };

// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

console.log('retrievedObject: ', JSON.parse(retrievedObject));

How to check whether a Storage item is set?

The getItem method in the WebStorage specification, explicitly returns null if the item does not exist:

... If the given key does not exist in the list associated with the object then this method must return null. ...

So, you can:

if (localStorage.getItem("infiniteScrollEnabled") === null) {
//...
}

See this related question:

  • Storing Objects in HTML5 localStorage

Speed/cost of localStorage

For what it's worth, here is a jsperf test.

The benchmark usage of localStorage is significantly slower than access of a regular object properties in both FF7 and IE9. Of course, this is just a micro-benchmark, and does not necessarily reflect real-world usage or performance...

Sample pulled from my FF 7 run to show what "significantly slower" means, in ops/second:


native local-storage notes
small set 374,397 13,657 10 distinct items
large set 2,256 68 100 distinct items
read-bias 10,266 342 1 write, 10 reads, 10 distinct items

Also, there are restrictions on what can be put in localStorage. YMMV.

Storing Objects in localStorage

local storage limited to handle only string key/value pairs you can do like below using JSON.stringify and while getting value JSON.parse

var testObject ={name:"test", time:"Date 2017-02-03T08:38:04.449Z"};

Put the object into storage:

localStorage.setItem('testObject', JSON.stringify(testObject));

Retrieve the object from storage:

var retrievedObject = localStorage.getItem('testObject');

console.log('retrievedObject: ', JSON.parse(retrievedObject));

Angular 6: saving data to local storage

You should define a key name while storing data to local storage which should be a string and value should be a string

 localStorage.setItem('dataSource', this.dataSource.length);

and to print, you should use getItem

console.log(localStorage.getItem('dataSource'));

Why is localStorage[...] undefined, but localStorage.getItem(...) is null?

The Web Storage Specification requires that .getItem() returns null for an unknown key.

Note however that .getItem() and .setItem() are specifically defined in the IDL as being the designated getter and setter for the Storage interface, and therefore they're also fully supported ways of accessing the contents of the storage.

However the [] syntax is more akin to a normal object and/or array property getter, and like those returns undefined for an unknown property name.

The reason not to use [] syntax is that it will operate on object properties first and will quite happily allow you to overwrite real properties and methods of the localStorage object, c.f:

> localStorage['getItem'] = function() { return 0 }
> localStorage.getItem('getItem')
0

How to delete a localStorage item when the browser window/tab is closed?

should be done like that and not with delete operator:

localStorage.removeItem(key);

localStorage get value using angular

In your loop you have an object, so just access id property like you do with an object: object.yourProperty or object[yourProperty]

var values = JSON.parse(localStorage.getItem("store_owner_ad_contacts"));

values.forEach(values, function(item, i) {

// you get object like this {id: "100033"}
// so to access id do like normal object

if (item.id === '100033') {
// do something
}

});


Related Topics



Leave a reply



Submit