Re:30 seconds of code: Curated list of useful JavaScript sni...
by danso on Monday December 11, 2017 @02:22PM
(#15899516)
Ahhh. I think I was confused why referring to `window.location.href` would be needed to be put into a function, and then called as `currentUrl()`, rather than having currentUrl be a string value. Is this best practice? I mean, is there some `window.location.href` isn't a global object?
[ Parent
| on HN ]
Re:30 seconds of code: Curated list of useful JavaScript sni...
by wereHamster on Monday December 11, 2017 @03:30PM
(#15900163)
Because the value may change. If 'currentUrl' was a constant (eg. `const currentUrl = window.location.href`) it would capture the href at the start of the application, even though it might change later on (history API, pushstate etc).
Re:30 seconds of code: Curated list of useful JavaScript sni...
by cag_ii on Monday December 11, 2017 @05:42PM
(#15901346)
Why wouldn't you just reference `window.location.href` when needed, instead of wrapping it up in `currentUrl`?
Re:30 seconds of code: Curated list of useful JavaScript sni...
by danso on Monday December 11, 2017 @06:11PM
(#15901607)
Yeah that was my question. I was racking my head thinking of when this window.location.href wouldn't refer to what a program would want given how it almost acts like a global function in some ways (e.g. `window.location.href="http://example.com"` can be used to change the page). Maybe currentUrl is supposed to be a wrapper just incase window.location.href changes (which seems highly unlikely but again, I'm out of the loop with modern JS).