The script
tag is just that...An HTML tag. As such, it doesn't have a scope because it's not JavaScript, it's HTML. What the script
element does for your is allows the HTML parser to "stand down" and have the JavaScript interpreter take over. The JS within the script
tag will execute according to standard JS rules. That means that references will be evaluated via the normal scope chain process.
In essence, everything in JS is global unless you code it to be otherwise.
Keep in mind that window
is not part of JavaScript. It's an API provided by browsers, so when we talk about "global", we are not always talking about window
. In node.js, for example, there is no window
or document
, but there still is a global scope. So, in JS, you can have globals, but that doesn't mean that they are automatically attached as properties of the window
object.
- Globals in JS are accessible by simply stating their reference name.
- Any HTML element with an
ID
attribute will become a property of thewindow
object. - Any JS property explicitly created as part of the
window
object will be available via thewindow
object. - Any HTML element that is part of the page that is loaded will be
accessible via a DOM API (i.e.,
document.querySelector
,document.getElementById
).
This is another answer from a while back that talks about the "scope chain" and how it works.
As @Teemu points out in the comments below, when you have a script type="module"
, things work a bit differently. See this link for more details.