If the user's browser is IE, and the localStorage doesn't already exist, the following code sets a localStorage, which has an expiry date of 24 hours.
(function ieAlert() {
var lastclear = window.localStorage.getItem('myLocalStorage'),
time_now = (new Date()).getTime();
var isIE = document.documentMode
if (isIE && !lastclear) {
if ((time_now - lastclear) > 1000 * 60 * 60 * 24) {
window.localStorage.clear()
window.localStorage.setItem('myLocalStorage', time_now)
}
}
})()
It works. But what I don't understand is this part:
if (isIE && !lastclear) {
if ((time_now - lastclear) > 1000 * 60 * 60 * 24) {
window.localStorage.clear()
window.localStorage.setItem('myLocalStorage', time_now)
}
}
Here the lastclear
is undefined, how does the calculation works then?
Here the
lastclear
is undefined, how does the calculation works then?
No, it's null
. getItem
returns null
for entries that don't exist. In a numeric context, null
coerces to 0
, so number - null
is number - 0
is number
.
(Whereas if the original author had accessed it the other way, localStorage.myLocalStorage
, the value would indeed have been undefined
, and the >
wouldn't work because number - undefined
is NaN
, and all comparisons with NaN
result in false
.)
If I were writing the code, I wouldn't rely on that null
coercion part of it, not least because it trips up future readers of the code (as it tripped you up). But that's why it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With