Reputation: 9714
I saw this in the diveintohtml5 website. This is how they check to see if localstorage is supported on the browser.
return 'localStorage' in window && window['localStorage'] !== null;
Would this be the same as just doing?
return window.localStorage != undefined
Upvotes: 3
Views: 6735
Reputation: 185883
1
return 'localStorage' in window && window['localStorage'] !== null;
This returns true if the window
object contains a property with the name localStorage
and the value of that property is not null
.
2
return window.localStorage != undefined
This returns true if the window
object contains a propety with the name localStorage
and the value of that property is not undefined
or null
(I am assuming that the global property undefined
holds the value undefined
)
Upvotes: 8
Reputation: 6210
Same result anyhow since if window.localStorage
is undefined
you will both get false
. And if window.localStorage
is null you will both get false
because undefined == null
.
However, I prefer using !!
just because it's the fastest way to convert to a boolean and how useful is localStorage if it's false, null, undefined, '', NaN or 0?
return !!window.localStorage;
Edit
One caveat, they are not exactly the same since if you set window.localStorage
to undefined
the first would report it as true
Upvotes: 5
Reputation: 2841
You can use Modernizr (1.1 or later) to detect support for HTML5 local storage.
if (Modernizr.localstorage) {
// window.localStorage is available
} else {
// no support for local storage
}
Upvotes: 1
Reputation: 9505
I wish you to recommend the following function:
function getLocalStorage(){
if (typeof localStorage == “object”){
return localStorage;
} else if (typeof globalStorage == “object”){
return globalStorage[location.host];
} else {
throw new Error(“Local storage not available.”);
}
}
If you want to read about global storage, compare it with local storage, Look at "JavaScript for Web Developers", chapter 19. It describes client local storages, comparing it with cookies.
Upvotes: 0