DEV Community

Pacharapol Withayasakpunt
Pacharapol Withayasakpunt

Posted on

Is it safe to use let or const in a <script> tag without a bundler?

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>
Enter fullscreen mode Exit fullscreen mode

index.js

let i = 1
Enter fullscreen mode Exit fullscreen mode

Actually, I have tried parcel.js and it auto-converts let to var even in raw <script> tags...

Top comments (4)

Collapse
 
vonheikemen profile image
Heiker

Makes sense. By itself a script tag doesn't create a scope, so if you created i outside of any function in index.js then it's part of the global scope, and that means that other scripts can't create another i in the global scope.

But if you create a block scope in the second script it should run. Something like this.

<script src="index.js"></script>
<script>
{
  let i = 1
}
</script>
Collapse
 
moopet profile image
Ben Sinclair

There's also no good reason for index.js to be creating variables with global scope unless they're unique names, like frobinator might put all its configuration under window.frobinator. Throwing random variable names around in global scope is asking for trouble.

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

But, in reality, how often do non-Node.js dev writes an outer brace in index.js, like if you use Flask or PHP.

<script src="index.js"></script>
// index.js

"use strict"
{
   ...
}

Versus, no braces, no use-strict, of course?

Also, I use to debug in Flask using global variables...

Thread Thread
 
vonheikemen profile image
Heiker

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.

(function () {
 /*
  * everything goes inside this
  */
})()

If you want to make something available to other scripts you use the return value of that.

window.my_unique_name = (
/*
* everything goes inside this
*/
)()

Global variables might be convinient but they can cause really terrible bugs. Just use them carefully.