Are Top-Level Variables Declared with const/let Not Supposed to Be Available to Code in Other Script Tags?

Yes, variables declared with const and let at the top level in one <script> tag are not accessible in another <script> tag. This behavior is due to JavaScript's block scoping and module behavior. Let’s explore why this happens and how to work around it.

Are Top-Level Variables Declared with const/let Not Supposed to Be Available to Code in Other Script Tags?
Yes, variables declared with const
and let
at the top level in one <script>
tag are not accessible in another <script>
tag. This behavior is due to JavaScript's block scoping and module behavior. Let’s explore why this happens
Understanding the Scope
In JavaScript, variables declared with var
in a script tag become properties of the window
object, making them accessible globally. However, const
and let
are block-scoped and do not attach themselves to window
.
Example:
<script>
var globalVar = "I am global";
let blockLet = "I am block-scoped";
const blockConst = "I am also block-scoped";
</script>
<script>
console.log(globalVar); // ✅ Works
console.log(blockLet); // ❌ Uncaught ReferenceError
console.log(blockConst); // ❌ Uncaught ReferenceError
</script>
Here, globalVar
is accessible in the second <script>
tag because var
attaches to window
, but blockLet
and blockConst
are not because they are not global.
Why Does This Happen?
Block Scope: Unlike
var
,let
andconst
are confined to their own script tag and do not leak into the global scope.Module Mode: If you use
<script type="module">
, each script executes in its own scope, making it behave like an ES6 module.
How to Share Variables Across Script Tags
Solution 1: Use window
Object Explicitly
You can manually attach variables to window
to make them accessible globally.
<script>
window.sharedVar = "Accessible in other scripts";
</script>
<script>
console.log(window.sharedVar); // ✅ Works
</script>
Solution 2: Use var
(Not Recommended)
Declaring with var
makes variables global, but this is not recommended due to potential conflicts.
<script>
var sharedVar = "I am global";
</script>
<script>
console.log(sharedVar); // ✅ Works but risky
</script>
Solution 3: Use ES6 Modules
For better modularity, use <script type="module">
and export/import variables.
<script type="module">
export const sharedValue = "Shared across modules";
</script>
<script type="module">
import { sharedValue } from "./your-script.js";
console.log(sharedValue);
</script>
Conclusion
Top-level variables declared with const
or let
inside a script tag are not accessible in another script tag due to scoping rules. To share data, use window
, var
(not recommended), or modular JavaScript with type="module"
.
Understanding these scoping rules helps write cleaner, more maintainable JavaScript code!
Let me know if you have any questions!