Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't understand why this code is working

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?

like image 962
user1941537 Avatar asked Dec 22 '22 22:12

user1941537


1 Answers

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.

like image 140
T.J. Crowder Avatar answered Jan 02 '23 22:01

T.J. Crowder