I find that running let i = 1
two times in a row throws an error, whether it is inside the <script>
tag or index.js
, that is not covered by function() {}
So, this throws an error,
index.html
<script src="index.js"></script>
<script>
let i = 1
</script>
index.js
let i = 1
Actually, I have tried parcel.js
and it auto-converts let
to var
even in raw <script>
tags...
Top comments (4)
Makes sense. By itself a
script
tag doesn't create a scope, so if you createdi
outside of any function inindex.js
then it's part of the global scope, and that means that otherscript
s can't create anotheri
in the global scope.But if you create a block scope in the second
script
it should run. Something like this.There's also no good reason for
index.js
to be creating variables with global scope unless they're unique names, likefrobinator
might put all its configuration underwindow.frobinator
. Throwing random variable names around in global scope is asking for trouble.But, in reality, how often do non-Node.js dev writes an outer brace in
index.js
, like if you use Flask or PHP.Versus, no braces, no use-strict, of course?
Also, I use to debug in Flask using global variables...
No one does it, not even Node.js devs, I was just trying to ilustrate my point about global scope. In the old days before ES6 modules to create a scope people used functions, specifically Immediately-invoked Function Expression.
If you want to make something available to other scripts you use the return value of that.
Global variables might be convinient but they can cause really terrible bugs. Just use them carefully.