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
HTML5 LocalStorage: Checking if a key exists
Quoting from the specification:
The getItem(key) method must return the current value associated with the given key. If the given key does not exist in the list associated with the object then this method must return null.
You should actually check against null
.
if (localStorage.getItem("username") === null) {
//...
}
Check if exist any Key localStorage Javascript
if (Object.keys(localStorage).length === 0) {
alert('There is no key!');
}
LocalStorage - check if key exists
In JavaScript you have truthy and falsey. This means that every condition converts in an condition-statement to a boolean and represents true
or false
.
Explenation
If localStorage.regionCode
is an empty string if(localStorage.regionCode)
would converts to false
otherwise true
.
For more details you could read the blog post about truthy and falsey
Checking if localStorage item exists is not working
It looks like you forgot to serialize your object prior to storing in localStorage
, you need to use
localStorage.setItem('localStor', JSON.stringify(yourObject));
Then this should work as expected.
Since it appears that there is a rogue item in your localStorage
, you may want to reset localStorage
and try again:
localStorage.clear()
How to check if localStorage value is in array?
Just use the Array.includes
method instead - it's less confusing, more appropriately matches what you're looking for, and doesn't require jQuery.
if (lines.includes(curPostId)) {
// ...
Also note that you can simplify your syntax by assigning and getting from localStorage
's dot properties directly, for example:
var lines = JSON.parse(localStorage.lines || '[]');
// ...
localStorage.saveButton = $(this).attr('id');
// ...
localStorage.lines = JSON.stringify(lines);
Related Topics
Good Tutorial For Using Html5 History API (Pushstate)
How to Fix Getimagedata() Error the Canvas Has Been Tainted by Cross-Origin Data
How to Change CSS Property Using JavaScript
Capture Iframe Load Complete Event
Zoom in on a Point (Using Scale and Translate)
Find the Closest Ancestor Element That Has a Specific Class
After Submitting a Post Form Open a New Window Showing the Result
Remember and Repopulate File Input
Referenceerror: Event Is Not Defined Error in Firefox
Why Does Forms With Single Input Field Submit Upon Pressing Enter Key in Input
Losing Scope When Using Ng-Include