Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: script doesn't see global variable only in Safari

I have the following code:

mytemplate.html:

<script>
  const DEBUG = true;
</script>
<script type="module" src="mycoolscript.js"></script>

mycoolscript.js:

console.log(DEBUG);

Loading mytemplate.html works fine in Chrome and Firefox, but fails in Safari 13.1.1 with a Can't find variable: DEBUG error.

Wrapping the console.log() call like so also fails:

window.onload = () => {
  console.log(DEBUG);
}

I would like to understand why.

like image 835
principal Avatar asked Sep 21 '25 11:09

principal


1 Answers

My guess is that safari 13.1.1 defines a scope for that script tag and because const creates block scoped constants in javascript, the constant wont be available outside that script tag.

In that case using var instead of const should fix the issue.

like image 103
Donbob Avatar answered Sep 22 '25 23:09

Donbob