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
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
)
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
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
}
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.”);
}
}
- First check will be enough to make sure localStorage is availabe
- Some browsers still don't support local storage, but global storage. It has the same function set, but has some differences comparing with localStorga
- If none of storages is supported, throw exception.
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.