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
.
<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.
Block Scope: Unlike var
, let
and const
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.
window
Object ExplicitlyYou 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>
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>
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>
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!