0

I had found this code on Smashing Magazine:

window.browser = (function () {
  return window.msBrowser ||
    window.browser ||
    window.chrome;
})();

I had noticed that this expression seemed equal to this one:

browser=window.msBrowser||window.browser||window.chrome;

Side note on the above code

It was supposed to be used in a browser extension, but it doesn't work in background scripts because they don't support window. Some other code that should work is:

if(typeof msBrowser!=="undefined")var browser=msBrowser;
else if(typeof chrome!=="undefined")var browser=chrome;
else if(typeof browser==="undefined")throw "UnsupportedBrowserError";

Is there a reason that the author had written the code in the way above? Not knowing the answer, I just decided to keep it the way it is. If there is a reason, what is it, and if there isn't a reason, would it be safe to use the one line alternative or should I use something else?

Lakshya Raj
  • 1,669
  • 3
  • 10
  • 34
  • 2
    No, no benefit in this case. – VLAZ Jun 24 '21 at 21:24
  • no, you may have some variables named msBrowser or browse or chrome, and your small line will become a nightmare to debugg – Mister Jojo Jun 24 '21 at 21:24
  • Can you please post an answer (maybe with some elaboration?) so that I can accept the answer? – Lakshya Raj Jun 24 '21 at 21:25
  • 3
    "*I had noticed that this expression seemed equal to this one: `browser=msBrowser||browser||chrome;`*" the IIFE and that line are not equivalent. If `msBrowser` is not a variable, for example, your replacement line will throw an error. The equivalent is `window.browser = window.msBrowser || window.browser || window.chrome;` – VLAZ Jun 24 '21 at 21:26
  • @VLAZ: Oops, going to fix that now, thanks for noticing! – Lakshya Raj Jun 24 '21 at 21:26

0 Answers0