DEV Community

Discussion on: Vanilla JavaScript localStorage

Collapse
 
merri profile image
Vesa Piittinen

And here is the shortest code to check to see if you can actually use the localStorage:

// usage: put return value to a variable or use as a if condition
!function(l){try{(l=localStorage).removeItem(l._='_')}catch(e){return 1}}()

You could also write a wrapper that would take care of cases like running out of localStorage space, but that is quite an overkill for most use cases. In the other hand if you do have lots of localStorage usage and/or need the abstraction (for code readability/maintenance reasons) then it will probably be worth it over a simple boolean check like the above.

Collapse
 
dailydevtips1 profile image
Chris Bongers

Very nice quick check! Love it <3